LearnFrenzy
Sign in Take a free test

Operators and Expressions · Find the Error · Question 7

Bug: a macro without brackets changes the precedence Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

The program should print 12 (double of 3, times 2). What does it print, and why?

main.c
#include <stdio.h>

#define DOUBLE(x) x + x

int main(void) {
    printf("%d\n", DOUBLE(3) * 2);
    return 0;
}
  • A 12
  • B 9 – the expansion is 3 + 3 * 2, and * binds before + Correct
  • C 6
  • D It does not compile
Correct Answer: Option B

A macro pastes text; precedence then applies to the result. Bracket the whole body and each parameter: #define DOUBLE(x) ((x) + (x)) – or use an inline function.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links