dilettant
dilettant

Reputation: 399

Get type name as string in C, GCC

Is there some 'builtin' extension in GCC to get type name of expression in C? (As a string, i.e. 'const char*').

Upvotes: 19

Views: 4943

Answers (3)

Dmytro Sirenko
Dmytro Sirenko

Reputation: 5083

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.

Upvotes: 4

Steve Jorgensen
Steve Jorgensen

Reputation: 12341

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?

Upvotes: 3

Cédric Julien
Cédric Julien

Reputation: 80751

Maybe you could have a look to the TYPE_NAME macro which seems to be a good starting point.

Upvotes: 3

Related Questions