LearnFrenzy
Sign in Take a free test

C Variables · Find the Error · Question 1

Using an uninitialised local variable as a total Answer, explanation & discussion

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

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

main.c
#include <stdio.h>

int main(void) {
    int sum;
    for (int i = 1; i <= 5; i++)
        sum += i;
    printf("%d\n", sum);
    return 0;
}
  • A The loop should start at 0
  • B sum is never initialised, so it starts with garbage and the total is unpredictable Correct
  • C sum must be static
  • D There is no bug; it prints 15
Correct Answer: Option B

Local variables are not zeroed. Write int sum = 0;. Compilers warn ("variable 'sum' is uninitialized when used here") – never ignore that warning.

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