C Programming Basics
int f(void) {
static int s = 0;
int a = 0;
s++;
a++;
return s * 10 + a;
}When the function f above is called three times in a row, which of the following is the return value of the third call?
- A11
- B13
- C31
Show answer and explanation
Answer: C. 31
The static local variable s is initialized to 0 only once, before the program starts, and keeps its value after the function returns. So s increases to 1, 2 and 3 with each call. a, without static, is created anew at each call and starts from 0, so it is 1 every time. The return value of the third call is 3 × 10 + 1 = 31.
- A. This is the value obtained if s also starts from 0 at each call. A static variable keeps its value.
- B. This is the value obtained by swapping the behavior of the static s and the non-static a (s = 1, a = 3).
- C. Correct. s increases to 3 and a is 1 every time, so 3 × 10 + 1 = 31.