The preprocessor performs a simple replacement of the text in the source code. He knows nothing about the base language or its rules.
In your example, SQ(2 + 3) expands to (2 + 3*2 + 3) , which evaluates to 11 .
A more reliable way to determine SQ :
Now SQ(2 + 3) will expand to ((2 + 3)*(2 + 3)) , giving 25 .
Although this definition is an improvement, it is still not bulletproof. If SQ() been applied to an expression with side effects , this can have undesirable effects. For instance:
- If
f() is a function that outputs something to the console and returns int , SQ(f()) , the result will be printed twice. - If
i is an int variable, SQ(i++) leads to undefined behavior .
See Macros for more examples of macro difficulties.
For these reasons, it is usually preferable to use functions rather than macros.
source share