ProgrammingEasyWipro · Capgemini pattern

What is printed?

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

Correct answer: C. 1 2 3

A static local variable is initialised once and keeps its value between calls, so the counter goes 1, 2, 3. Without static, id would be re-created as 0 on every call and each call would return 1.

More C Programming questions

Exams that ask this topic