C Programming Basics
#define SQUARE(x) x * x
int a = 3;
printf("%d\n", SQUARE(a + 1));Which of the following is the output when the code above, which uses the macro SQUARE defined with #define, is executed?
- A7
- B10
- C16
Show answer and explanation
Answer: A. 7
A macro is only a text replacement done by the preprocessor. SQUARE(a + 1) expands to a + 1 * a + 1, and the multiplication is evaluated first, giving 3 + 3 + 1 = 7. To get the intended square of (a + 1), 16, put parentheses around the argument and the whole body, as in #define SQUARE(x) ((x) * (x)). Even then, an argument with side effects such as SQUARE(i++) evaluates i++ twice and becomes undefined behavior, so an inline function can be used instead.
- A. Correct. It expands to a + 1 * a + 1, which is 3 + 3 + 1 = 7.
- B. This is the value obtained by misreading it as SQUARE(a) + 1, that is, 3 × 3 + 1.
- C. This is the value of (a + 1) × (a + 1). A macro is replaced without adding parentheses.