Type Overload Macro

I have a bunch of macros for debugging printf debug, and it would be great not to specify the type, is there anything you can do to something like macro overloading in c (gcc can be specified if available in gcc 4 , 3). I thought maybe typeof, but apparently this doesn't work.

Macro example (I also have some colors that I cannot remember at the top of my head)

#ifdef _DEBUG #define DPRINT_INT(x) printf("int %s is equal to %i at line %i",#x,x,__LINE__); . . . #else #define DPRINT_INT(x) . . . #endif 
+7
source share
3 answers

Try it; it uses the gcc __builtin methods and automatically detects the type for you as much as possible and makes a simple DEBUG macro where you do not need to specify the type. Of course you can compare typeof (x) with a floating point, etc. Etc.

 #define DEBUG(x) \ ({ \ if (__builtin_types_compatible_p (typeof (x), int)) \ fprintf(stderr,"%d\n",x); \ else if (__builtin_types_compatible_p (typeof (x), char)) \ fprintf(stderr,"%c\n",x); \ else if (__builtin_types_compatible_p (typeof (x), char[])) \ fprintf(stderr,"%s\n",x); \ else \ fprintf(stderr,"unknown type\n"); \ }) 
+9
source

What about the next macro? You still need to choose the print format, but you don’t have to redefine all the possible cases, and it also works on MSVC:

 #define DPRINT(t,v) printf("The variable '%s' is equal to '%" ## #t ## "' on line %d.\n",#v,v, __LINE__) 

To use it:

 int var = 5; const char *str = "test"; DPRINT(i,var); DPRINT(s,str); 
+1
source

I think you can try with the following code:

 #define DPRINT(fmt) do{ \ my_printf fmt ; \ } while(0) my_printf( const char* szFormat, ... ) { char szDbgText[100]; va_start(args, szFormat); vsnprintf(&szDbgText,99,szFormat,args); va_end(args); fprintf( stderr, "%s", szDbgText ); } // usage func( ) { int a = 5; char *ptr = "hello"; DPRINT( ("a = %d, ptr = %s\n", a, ptr) ); } 

Note. Using DPRINT here takes double parentheses.

0
source

All Articles