Is it possible to create a C preprocessor macro that evaluates to an increasing number depending on how often it was called? It should be compile-time only.
I'd like something like:
#define INCREMENT() ....
#define INCRVALUE ....
INCREMENT()
INCREMENT()
i = INCRVALUE;
// ...
INCREMENT()
// ...
j = INCRVALUE;
and afterwards i == 2 and j == 3.
The C pre-processor works with text. It can't do any kind of arithmetic because it does not know how and even if it did, you can't assign to rvalues like literals (e.g. 5 = 5+1
or ++5
).
A static
variable would be much better.
GCC provides a macro, __COUNTER__
, which expands to an integer representing how many times it's been expanded but that's not ISO C.
#define CNT __COUNTER__
#define INCREMENT() CNT
INCREMENT();
INCREMENT();
int i = CNT;
// i = 2
Boost may help if you need it to be portable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With