3 ms·
__EXP_COUNTER__ has a stable value in a given token replacement sequence (right hand side of a macro). __COUNTER__ __COUNTER__ __COUNTER__ might give you 42 43
by kazinator 4y ago
__EXP_COUNTER__ has a stable value in a given token replacement sequence (right hand side of a macro).
__COUNTER__ __COUNTER__ __COUNTER__ might give you 42 43 44, whereas __EXP_COUNTER__ __EXP_COUNTER__ __EXP_COUNTER__ will produce 73 73 73.
We can imagine that every macro has a hidden parameter:
#define MAC(A, B, C, __EXP_COUNTER__)
we don't pass this parameter when calling the macro; the macro expander does that, and it passes an integer token whose value is incremented for each such call.
- jstimpfle 4y agoThanks, it's a little clearer in my mind now. But wouldn't this work for you? #include <stdio.h> #define FOO_(c) printf("%d %d %d\n", c, c, c); #define FOO() FOO_(__COUNTER__) #define FOO2() FOO_(__COUNTER__) int main(void) { printf("%d %d %d\n", __COUNTER__, __COUNTER__, __COUNTER__); FOO(); FOO(); FOO2(); FOO2(); return 0; } Output: 0 1 2 3 3 3 4 4 4 5 5 5 6 6 6
- melissalobos 4y agoRight, but now you can't use that COUNTER value in a macro and have it stay the same value. Think about concatenating a variable name with the counter and trying to use that same new name later in the same macro. Like NAME ## __COUNTER = NAME ## __COUNTER -1; This won't work without some extra state.
- jstimpfle 4y agoThis code won't work in any case. You can't do arithmetic like that. And I think it's much better code anyway to create the expansion once, because otherwise you have to construct NAME ## __COUNTER at each use and it quickly becomes unmaintainable and hard to change how you construct that name. IMO the best solution if you want to avoid an extra indirection to inject some state, would be preprocessor variables that you can assign to in a macro expansion. Procedural preprocessor code basically. But the preprocessor doesn't work like that.