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?

  1. A7
  2. B10
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. The header file sensor.h is written as above. Which of the following is the purpose of the three lines #ifndef, #define and #endif?
  2. Which of the following is the output when the code above is written inside the main function and executed?
  3. A microcontroller output register is declared and used as above. Which of the following correctly describes this declaration?
  4. Which of the following describes undefined behavior as defined by the C standard?
  5. int and unsigned int are 32 bits. Which of the following is undefined behavior according to the C standard?