Why can't GCC's typeof() be stringified?

213 views Asked by At

I'd like to print the type that typeof() outputs, but typeid is only available in C++. Why can't I use stringification to get the name of this type?

#define GET_STRING(s) #s

#define example(input)                              \
    do {                                            \
        char test[20] = GET_STRING(typeof(input));  \
        printf(test);                               \
    }                                               \
    while (0)                                       \

This would print out "typeof()" with input stringified inside. Why does the preproccessor stringify before typeof() is handled? Is there a way to override this behavior?

You can stringify types directly if they are passed like GET_STRING(int), so using typeof() should have the same behavior.

1

There are 1 answers

0
n. m. could be an AI On

Why does the preproccessor stringify before checking typeof()?

There is this "pre" prefix in "preprocessor", it means "before". The preprocessor works before most everything else. Here is the ordered list of translation phases. Note "Preprocessing directives are executed, macro invocations are expanded" comes under #4, and "Each preprocessing token is converted into a token. The resulting tokens are syntactically and semantically analyzed and translated as a translation unit" under #7.

Is there a way to override this behavior?

No.

You can stringify types directly if they are passed like GET_STRING(int), so using typeof() should have the same behavior.

The behaviour of the compiler is governed by the language standard, rather than by nebulous wishes of the users. You should quote the standard before making an assertion about what a compiler should or should not do. If you don't like what the standard says, you can write a proposal to amend it and wait for it to be accepted (but I wouldn't hold my breath).

Here is what the standard says about stringifying:

[...] the original spelling of each preprocessing token in the stringizing argument is retained in the character string literal [...]

The original spelling of the typeof token in your program is "typeof", so that's what gets inside the string literal.