How do I get a variable's type in c? Objective c has className, php has get_class(), etc...
Good luck with that. C will cast any block of memory to any data type you like. It doesn't really understand types per se.
You look in the source code and find the type; since there's no dynamic types in C the static type is all there is.
You can't do it. C provides absolutely no way to get to the type of a variable.
One way you can do it is to use the sizeof
operator to get the size of the variable, and then based on this, you can make "assumptions" about what the variable is.
I don't think this would help you with pointers though, since my intuition is that all pointers have the same size, no matter what they are referencing.
Since it is impossible* to have a variable of unknown type in C, there is no need for this. There is no equivalent of id
for C types. It's possible to have a void-pointer to memory whose intended type you don't know, but it has to be cast to a pointer to a specific type in order to actually have any specific type — until then, it's just an address.
There are places where more polymorphism would be useful, but C just doesn't have it.
(*Note: I'm discounting unions, since they are a type all their own and the real question is what type you want to get out of it.)
As the other answers have said, C provides no dynamic, runtime type inspection - all typing is performed at compile time. If you need runtime type determination in C, them you'll need to build that yourself somehow.
Some examples,
- putting a tag in a structure that indicates the type.
- using other data like the format specifier string in
printf()
to indicate the type
These are the kinds of things that you might need to do if you're serializing data to/from a file, for example. Unfortunately, you get pretty much no help from the compiler or the standard library. A third party serialization library might help, but that would really depend on exactly what it is you want to do.