ProgrammingModerateAccenture · Capgemini pattern

What is printed?

What is printed?
int tick(int reset) {
    static int c = 10;
    if (reset) c = 0;
    return c += 2;
}
int main(void) {
    int a = tick(0);
    int b = tick(1);
    int c = tick(0);
    printf("%d %d %d", a, b, c);
}
  1. A. 12 2 4
  2. B. 12 12 14
  3. C. 2 2 4
  4. D. 12 2 2

Correct answer: A. 12 2 4

A static local is initialised once, before the first call, and keeps its value between calls; the initialiser does not run again. Call 1: 10 + 2 = 12. Call 2 resets to 0, then 2. Call 3 continues from 2 to 4. The main's local c is a different variable.

More C Programming questions

Exams that ask this topic