LearnFrenzy
Sign in Take a free test

Declarations and Initializations · Find the Error · Question 3

Error: global variable initialised with a function call Answer, explanation & discussion

  • Find the error
  • Medium
  • 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 get_limit(void) { return 50; }

int limit = get_limit();

int main(void) {
    printf("%d\n", limit);
    return 0;
}
  • A get_limit must be static
  • B Objects with static storage must be initialised with constant expressions; a function call is evaluated at run time Correct
  • C limit must be const
  • D There is no bug
Correct Answer: Option B

Globals are initialised before main() runs, from values known at compile time. Assign at run time instead (int limit; … limit = get_limit(); in main), or use a constant.

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