ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int f(void) {
    static int x;
    return x++;
}
int main(void) {
    printf("%d %d %d", f(), f(), f());
}
  1. A. 0 1 2, guaranteed left-to-right
  2. B. Compilation error: static must be explicitly initialized
  3. C. 2 1 0, guaranteed right-to-left
  4. D. Some unspecified permutation of 0, 1, 2 (argument evaluation order is unspecified, but static x deterministically reaches 0,1,2 across the three calls)

Correct answer: D. Some unspecified permutation of 0, 1, 2 (argument evaluation order is unspecified, but static x deterministically reaches 0,1,2 across the three calls)

A static local without an explicit initializer is zero-initialized once, then persists; x++ returns the pre-increment value, so the three calls return 0, 1 and 2 in some order, but C does not fix which printf argument is evaluated first, so the visible order among the three printed numbers is unspecified (though each call does correctly observe x incrementing once).

More C Programming questions

Exams that ask this topic