I want to define a macro at compile time based on the value of another macro. However this code is not executing as expected:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIXTEEN 16
#define TWO (SIXTEEN % 8 == 0)? (SIXTEEN / 8) : ((SIXTEEN / 8) + 1)
int main();
int main() {
printf("max = %d\n", TWO);
int i;
for (i = 0; i < TWO; i++) {
printf("%d\n", i);
}
return 0;
}
This prints:
max = 2
0
1
2
...
and continues until terminated, When it should be printing simply:
max = 2
0
1
and exiting.
If I do this instead, it works:
#define TWO 2
I thought that this was an issue with the macro’s definition… however, if I do the following with the original #define, it seems to work:
...
int count = TWO;
for (i = 0; i < count; i++) {
...
Can anyone explain what’s going on here?
The problem is that the token
TWOis replaced by the tokens with which you defined the macro, so this:becomes this:
Because of operator precedence, this is read as:
You need extra parentheses so that when
TWOis replaced by its replacement list, you get the result you want:When using macros, it’s best to use parentheses wherever you can to ensure the result is what you expect.