The C standard does not allow this directly. The C++ standard has some ability to do this (dynamic_cast
and typeid
).
typeof
GCC comes with a typeof operator that may be useful depending on what you're doing.
conditional operator
The conditional operator (the question mark and colon in expressions like x = y == 0 ? 1 : 0;
) has some ability to tell you if two types can be coerced into a third type (that article is about C++, but the type safety of the conditional operator is the same in C). Its use is nonobvious to say the least.
Both of these techniques (typeof
and the conditional operator) are limited to what information is available at compile time. That is, you can't pass a void*
to a function and then use typeof
to figure out the original type of the object the pointer points to inside that function (because such information isn't available inside that function at compile time).
Thinking more about this, GTK+ is written in C and has a system you may consider emulating. It looks like they use type IDs, but instead of putting the IDs in the struct, they use macros to look things up.