Question

Currently, I have a scenario much like this:

#define my_macro(var) __builtin_types_compatible_p(typeof(var), foo) ? do_something : do_something_else

However, inadvertently the macro gets passed this parameter:

my_macro(int x);

Which of course fails, because typeof(int x) isn't valid.

Is there a transformation I can apply inside the my_macro which will allow typeof to work on that expression? I cannot change what is passed into the macro, only what happens inside the macro.

So, something like this:

#define my_macro(var) typeof(?? var ??)

Or, is there another expression I should be using here?

Was it helpful?

Solution

Well, I found a way to do it, using yet another GCC extension, this time the statement expression:

#define my_typeof(definition) typeof(({ definition, _def; _def; }))

Which, of course, expands to:

typeof(({ int x, _def; _def; }))

Pretty ugly, but why do I care? It works.

OTHER TIPS

You could handle x or int x separately but to handle both with one macro you would need the ability to parse/separate a space-delimited argument within the C preprocessor. To my knowledge, no such support exists in the C preprocessor. Without such parsing capabilities you must find some other clever way to write a macro that works around this limitation, for example, something in the spirit of my_macro2() in the following code sample:

#include <stdio.h>

#define my_macro1(var) \
do { \
   typeof(var) blah; \
   printf("sizeof(var)=%d\n", sizeof(blah)); \
} while(0)

#define my_macro2(var) \
do { \
   var, newvar_sametype; \
   typeof(newvar_sametype) blah; \
   printf("sizeof(newvar_sametype)=%d\n", sizeof(blah)); \
} while(0)


int
main()
{
   int x;
   my_macro1(x);
   my_macro2(char y);

   return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top