tags:

views:

77

answers:

6

How do I get a variable's type in c? Objective c has className, php has get_class(), etc...

+1  A: 

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.

cs80
+5  A: 

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.

R Samuel Klatchko
+3  A: 

You can't do it. C provides absolutely no way to get to the type of a variable.

Johannes Schaub - litb
+1  A: 

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.

chustar
+1 for the creativity. About the pointers, you can dereference them and then sizeof
klez
Thanks. Forgot about dereferencing, though.
chustar
Dereferencing them doesn't help though, as you'll only get the size of the type of the pointer (i.e., even if char *foo is actually a pointer to an int, it will dereference as a char, and return that size), which would most likely be visible in the code anyway. Of course this is all due to what everyone else is saying in that you can't have 'unknown' types.
bobDevil
Faulty creativity. On some platforms `float` and `double` have the same size as `int`, `long` or `long long`. Also, variables can be `struct`s and a `struct` can be created to have the same size as an `int`. Difficult. Might be easier *turning hamburger into a cow*.
Thomas Matthews
A: 

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.)

Chuck
+1  A: 

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.

Michael Burr