J
James Kuyper
Nick said:I can't see how you can be unaware of the type of a variable
in normal C. There must be a declaration/definition in scope.
Unless gcc has added some sort of anonymous type
Lets say the code has #included a standard header that defines size_t.
How would you determine whether or not it's a typedef for unsigned long?
You could check the header file (if it is in fact available as a
separate file - this is not required) or by reading the implementation's
documentation. However, it's not something your code itself could determine.
for instance, consider you've got a function that expects a pointer to
an array of unsigned long, and the program has an array of size_t. If
size_t is a typedef for unsigned long, it can just pass a pointer to the
original array. If not, it will have to take the slower approach of
copying each element of the first array into a second array of unsigned
long, and then pass a pointer to the second array to the function. In
code intended to be portable, I'd like it to use the faster method when
possible, and the slower method if necessary - but C provides no way of
determining this with certainty.
If the two types have the same size it is a pretty good indicator that
they might be the same. Having SIZE_MAX and ULONG_MAX be the same value
would be an even stronger clue. But even if both of those features
match, in principle it's possible that one is a big-endian type, and the
other is a little-endian type, or some other variation in the order of
the value bits.
In the most recent case where I've had to worry about something like
this, it was a third-party typedef (which varied depending upon which
platform the third-party library was installed on), so I didn't even
have *_MAX macros to rely upon, even if *_MAX would have been sufficient
to resolve the question.
void print (ANON x)
{
switch (typeof(x))
{
case int:
printf ("%d", (int)x);
break;
...etc...
}
}
this seems to do some violence to the fundamentals of C
As I understand it, the typeof which is a common extension to C can be
used only in the same places that a type name can be used; hence, not in
a switch statement. Therefore, it's not sufficient for the purpose I
outlined above. The C++ typeid operator, on the other hand, does return
a value of type std::typeinfo that supports equality comparisons. This
isn't suitable for switch(), but can be used in an extended if-else series.