Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the type of the variable in C at runtime?

Is it possible to check what type the variable is at any given point throughout the code?

For instance, say, i declare char y = 1; and function int SomeFunction (int). I then will pass y to someFunction, it will get converted to an int and ultimately int will be returned.

I know this because of function declaration. I would like, however to confirm that inside someFunction, variable is in fact of type int and variable returned from someFunction is as well an int.

Can this be done in C, or function declaration should be relied upon instead? Does C programming language provide any mechanism to check variable type at runtime?

like image 226
James Raitsev Avatar asked Dec 25 '11 19:12

James Raitsev


1 Answers

In your code, you can rely on the fact that the types you are handed correspond to how they were declared. You couldn't write any non-trivial program if that wasn't the case.

Type information, in C, is only available at compile time though. At runtime, none of that information is present so there is no standard build-in way of, for example, telling what type of object is hiding behind a random pointer.
If you need that kind of information, see if your compiler has extensions for it (I don't know if any do), or use frameworks that provide infrastructure for that (glib has things like that I believe).
Or roll your own if you really really need it.

Or use C++ which does have some runtime type information support, and generally speaking a more intricate type system, but that's a totally different language.

like image 109
Mat Avatar answered Nov 09 '22 00:11

Mat