5

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.

wonderingnewbie
  • 681
  • 4
  • 7
  • 3
    Does this answer your question? [C Preprocessor: Own implementation for \_\_COUNTER\_\_](https://stackoverflow.com/questions/22693565/c-preprocessor-own-implementation-for-counter) – user202729 May 23 '20 at 07:06

1 Answers1

5

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.

edmz
  • 8,220
  • 2
  • 26
  • 45
  • I was hoping the macro could add the string "+1" each time. But thank you for __COUNTER__. – wonderingnewbie May 17 '15 at 22:41
  • That's not possible because the preprocessor can't make additions. Are we still talking about integers or strings? – edmz May 18 '15 at 06:01
  • 1
    I was hoping that the preprocessor could create something like 1+1+1 and adding "+1" every time the macro is used. The compiler would then at compile time do the addition and create an integer. – wonderingnewbie May 28 '15 at 23:02