Question 5
Back to Exercise
The program below has a problem. Which statement correctly describes it?
#include <stdio.h>
int seed(void) { return 7; }
int next(void) {
static int s = seed();
return ++s;
}
int main(void) {
printf("%d\n", next());
return 0;
}
- A A static variable cannot be an int
- B static int s = seed(); – a static variable must be initialised with a constant, but seed() is a function call Correct
- C next() must be static too
- D There is no error; it prints 8
Correct Answer: Option B
Static variables are initialised before the program runs, so their initializer must be a constant expression. (C++ allows a function call here; C does not.) Initialise to a constant and set it on the first call instead.
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!