0

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.