What goes wrong when the macro #define SQ(x) ((x)*(x)) is invoked as SQ(i++)?
Correct answer
C. The argument is substituted twice, so i is incremented twice in one expression
15 views
C. The argument is substituted twice, so i is incremented twice in one expression
15 views
Macro substitution is textual, so SQ(i++) becomes ((i++)*(i++)), incrementing i twice and leaving the two reads unsequenced, which is undefined behaviour. The extra parentheses fix precedence only, never repeated evaluation; an inline function is the safe replacement. The same hazard makes MAX(a++, b) evaluate one operand twice depending on the comparison outcome.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is C? Ask here and get an explanation.