Sunday 28 October 2012

__COUNTER__ : An interesting macro

Hi,

Recently, i came across a macro, the __COUNTER__. In the past, i had looked for a way to do something that this macro allows us to do, but i wasn't aware of it at that time. So, i assumed its simply not possible to do it. 
I was searching for an easy way to generate variable names and this macro allows us to do just that.

Here is what the macro does. Everytime this macro is expanded, there is an internal count and the preprocessor writes this number.

To explain it further, here is an example:

 int main()  
 {  
   __COUNTER__  
   __COUNTER__  
   __COUNTER__  
   return 0;  
 }  

So, if you see the preprocessor output, you can see __COUNTER__ being expanded to 0, 1, 2.

1) In Visual Studio, to view the preprocessor output, you can goto Project Properties->C/C++->Preprocessor.  There you can select if you want to generate preprocessor output. It generates a ".i" file that contains the preprocessor output.

2) In GCC, you can give -E option to obtain the preprocessor output.

Now, here is an example how you can use it to obtain variable names. Its just a neat way to use them, instead of use giving foo, bar, baz...

#define var1(x, y)  x##y;  
 #define var(x, y)  var1(x, y)  
 int main()  
 {  
   int var(a, __COUNTER__)  
   int var(a, __COUNTER__)  
   return 0;  
 }   

This generates names like a0, a1 etc. Its just a nice way to use it. Well there could be several cases where this could come in handy. This was some instance where i wanted a neat way to generate names.

 

No comments :

Post a Comment