Reputation: 3
Here's the example code.
#define A 100
#define B A+1
I've been reading C basic books and the writer said that code could cause fatal problems and there is no explanation about it.
why this code has a problem? I want to understand
Upvotes: 0
Views: 67
Reputation: 782344
Suppose you try to write:
int foo = B * 10;
You probably expect this to set B
to 1010
. But it will actually set it to 110
because it expands to
int foo = 100+1 * 10;
Because of operator precedence, the multiplication is done first, so it's 100 + 10
, not 101 * 10
.
To prevent problems like this, you should put parentheses around the macro expansion.
#define B (A+1)
Then it will expand to
int foo = (100+1) * 10;
and you'll get the expected result.
Upvotes: 4