LearnFrenzy
Sign in Take a free test

C Const · Find the Error · Question 8

Bug: a macro without parentheses computes the wrong area Answer, explanation & discussion

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

The program should print the area of a square of side 1 + 1. What does it print, and why?

main.c
#include <stdio.h>

#define AREA(r) 3 * r * r

int main(void) {
    printf("%d\n", AREA(1 + 1));
    return 0;
}
  • A 12
  • B 5 – the macro expands to 3 * 1 + 1 * 1 + 1, because the argument is pasted as text Correct
  • C 6
  • D It does not compile
Correct Answer: Option B

Macros substitute text, not values. Bracket every parameter and the whole body – #define AREA(r) (3 * (r) * (r)) – or write a function, which also checks types.

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