LearnFrenzy
Sign in Take a free test

C Variables · Find the Error · Question 3

Error: defining the same variable twice in one scope Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#include <stdio.h>

int main(void) {
    int total = 0;
    int total = 5;
    printf("%d\n", total);
    return 0;
}
  • A total must be unsigned
  • B total is defined twice in the same block – a redefinition error; assign instead: total = 5; Correct
  • C The second line shadows the first
  • D There is no bug
Correct Answer: Option B

Shadowing only happens between different scopes. Two definitions of the same name in one block are an error. To change the value, assign: total = 5;.

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