Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type overloading macro

I have a bunch of printf debug helper macros and it would be pretty cool to have to not specify the type, is there anything you can do to allow something like macro overloading in c(can be gcc specific if its available in gcc 4.3). I thought maybe typeof but apparently that doesn't work.

example macro(I also have some ascii terminal color stuff that I can't remember of 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
like image 700
Roman A. Taycher Avatar asked Apr 12 '11 10:04

Roman A. Taycher


2 Answers

Try this; it uses gcc's __builtin methods, and automatically determines the type for you, as best it can, and makes for an easy DEBUG macro where you don't have to specify the type. Of course, you can compare typeof (x) to float, 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");                        \

  })
like image 143
Ben Stott Avatar answered Nov 09 '22 02:11

Ben Stott


How about the following macro? It still requires you to pick the print format but you won't have to redefine all possible cases and it works on MSVC as well:

#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);
like image 31
Mario Avatar answered Nov 09 '22 00:11

Mario