#include <stdio.h>
#define ONE 3 > 2 ? 16 : 64
#define TWO ONE/16
int main () {
printf("%d\n", TWO);
return 0;
}
I write two #define
, but output is 16, while I expected it was 1.
Why does this happen?
CodePudding user response:
Macros are a simple text replacement. When preprocessor goes through the code, it replaces
printf("%d\n", TWO);
with
printf("%d\n", ONE/16);
and then with
printf("%d\n", 3 > 2 ? 16 : 64/16);
Then compiler can see that ternary operator condition evaluates to true and takes the first result - 16
.
You probably wanted first macro to be wrapped in parentheses:
#define ONE (3 > 2 ? 16 : 64)
But I'd strongly suggest to avoid using macros wherever possible. As comments suggest,
constexpr auto ONE = 3 > 2 ? 16 : 64;
would give you the expected result.
CodePudding user response:
The preprocessor is only a simple text replacing.
If you replace it by hand or simply use the gcc -E
option ( maybe different on other compilers ) you get:
#define TWO 3 > 2 ? 16 : 64/16
What you expect is can be simply achieved by using braces:
#define ONE (3 > 2 ? 16 : 64)
#define TWO ONE/16
BTW: You should not longer use macros at all and replace it by compile time constant expressions like:
constexpr auto ONE = 3 > 2 ? 16 : 64;
The benefit is, that you get errors or warnings if you did something wrong and all expressions are type safe. Macros, as said, are only doing text replacement without any syntax check for the later on used language.