boredguy
boredguy

Reputation: 23

Preprocessor macros: any way to get a unique variable name and reuse it?

I am trying to use unique variable names every time my macro is expanded, I cannot come up with a solution

I have code something like this

#define _each(results,arr,i,v, f)\
  for (i=0;i<len(arr);i++){\
    v = arr[i];\
    f\
  }

I'd love to assign a unique variable name to I and V.

So when they are expanded i get

for(i1=0;i<len(arr);i++){ // first expansion
  v = arr[i1];
  // dostuff
}
for(i2=0;i<len(arr);i++){
  v = arr[i2];
  // do stuff
}

I've tried __Counter__ but i cant figure out how to reuse the variable

#define m(var1,var2) {\  // example calling use m(i,v)
  var1 ##__COUNTER__ ;\  // prints i1 
  row = array[var1];\    // prints i, need i1
  row = array[var1 ##__COUNTER__##]; // prints i2.. i need i1

If that makes sense..

I need to increment the variable names because i have one case where I nest the macro!

Upvotes: 2

Views: 2266

Answers (2)

rici
rici

Reputation: 241901

You can use __LINE__ instead of the (non-standard) __COUNTER__. __LINE__ is the current line number in the source file of the original text (not the macro replacement text). So it doesn't change during the expansion of a macro, and it will be different for each macro expansion provided:

  • You never expand the macro twice in the same source code line
  • You don't try this trick from two different source files.

Upvotes: 2

Greg A. Woods
Greg A. Woods

Reputation: 2792

Unless your real-world use case is far more complex than your example, there is no need for you to use unique variable names.

Keep it simple! Just define them as local names within a block:

#define foreach(results, array, len, function) \
    { \
        int i; \
    \
        for (i = 0; i < len; i++) { \
            unsigned int v; \
    \
            v = array[i]; \
            v = function(v); \
            results[i] = v; \
        } \
    }

In C every block effectively gets its own region of stack for those more locally scoped variables defined within it and so you can have as many i and v variables as you need -- one set for every expansion of your macro.

Upvotes: 1

Related Questions