Is there some 'builtin' extension in GCC to get type name of expression in C? (As a string, i.e. 'const char*').
-
1one would assume compile-time, because runtime would be plain weird – evgeny May 24 '11 at 13:15
-
Could you tell us why it is needed? – Nyan May 24 '11 at 13:18
-
1It is a pretty good question, though. I wanted to do something like that myself but never got around to it. It'd be nice to know if it's possible. – evgeny May 24 '11 at 13:19
-
Runtime. Something that will achieve for C what typeid(expression)::name() achieves for C++. – dilettant May 24 '11 at 22:21
-
Maybe, debugging information embedded in an object file may be of some help, but it's not a part of the language. – Dmytro Sirenko Dec 27 '12 at 21:07
-
See also http://stackoverflow.com/questions/1055452/ – Bunkar Oct 01 '13 at 19:05
3 Answers
First. You want to obtain type of a C expression at runtime. The problem is that types are erased during compilation and the machine code is almost typeless, it does not contains anything else than 8/16/32/64 bit integers and 32/64/80 bit floating point numbers (in case of x86). Types are compile time entity for C (C++ may retain some information about types in runtime though, because of its object-oriented nature, it associates types with classes, but it's hard to track PODs and primitive types).
Second. You want a type of a C expression. Sometimes it's hard to say what a given C expression be at runtime.
Thus there's no way to obtain C expression type at runtime.

- 5,003
- 21
- 26
-
Note that this is a more thorough and useful answer than the one I gave, IMO. – Steve Jorgensen Dec 27 '12 at 20:54
Since you said you want the name at runtime, that is a definitive "no". In C, data is just bytes in memory and doesn't have an intrinsic type at all. It is only the type declaration that tells the compiler what the compiled code should expect the type to be.
It would make sense, however, for a C compiler to be able to recognize the type of a variable at compile time, and that would be great for implementing things like equality assertions with friendly output in a unit testing framework. I can't see that C has anything like that either though.
Does anyone know if new versions of the ANSI C spec are still being developed? Compile-time type identification would be a great thing to add. Maybe integer constants for intrinsic types and a type equality test for either intrinsic or defined types?

- 11,725
- 1
- 33
- 43
Maybe you could have a look to the TYPE_NAME macro which seems to be a good starting point.

- 78,516
- 15
- 127
- 132
-
4That is internal to gcc, not something available within the source file being compiled. – mark4o May 24 '11 at 15:18