Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting preprocessor macro possible? [duplicate]

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.

like image 451
wonderingnewbie Avatar asked May 17 '15 17:05

wonderingnewbie


1 Answers

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.

like image 50
edmz Avatar answered Nov 17 '22 14:11

edmz