Can a preprocessor macro be read?

Is it possible to create a C preprocessor macro that will increment depending on how often it is called? It should only be compile time.

I would like something like:

#define INCREMENT() ....
#define INCRVALUE ....

INCREMENT()
INCREMENT()
i = INCRVALUE;
// ...
INCREMENT()
// ...
j = INCRVALUE;

      

and then i == 2 and j == 3.

+3


source to share


1 answer


The C preprocessor works with text. It cannot do any kind of arithmetic because it doesn't know how and even if it did, you cannot assign rvalues ​​as literals (like 5 = 5+1

or ++5

).

A static

will be much better.

GCC provides a macro __COUNTER__

that expands to an integer representing how many times it has been expanded, but not ISO C.



#define CNT __COUNTER__
#define INCREMENT() CNT

INCREMENT();
INCREMENT();
int i = CNT;  
// i = 2

      

Boost can help if you need it to be portable.

+2


source







All Articles