LearnFrenzy
Sign in Take a free test

C Variables · Find the Error · Question 7

Bug: a function accumulates into a global by mistake Answer, explanation & discussion

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

The function should return the sum of an array. Called twice on {1, 2, 3}, what does the program print, and why?

main.c
#include <stdio.h>

int total = 0;

int sum_array(const int *a, int n) {
    for (int i = 0; i < n; i++)
        total += a[i];
    return total;
}

int main(void) {
    int a[] = {1, 2, 3};
    printf("%d ", sum_array(a, 3));
    printf("%d\n", sum_array(a, 3));
    return 0;
}
  • A 6 6
  • B 6 12 – sum_array uses the global total, which is never reset, so the second call adds onto the first result Correct
  • C 12 12
  • D It does not compile
Correct Answer: Option B

The function forgot to declare its own accumulator and silently uses the global. Declare int total = 0; inside the function – and avoid mutable globals so mistakes like this cannot compile.

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