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());
}- A. 0 1 2, guaranteed left-to-right
- B. Compilation error: static must be explicitly initialized
- C. 2 1 0, guaranteed right-to-left
- 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
- What is printed? c static int helper(int n) { return n 2; } int main(void) { printf("%d", helper(5)); }
- What is printed? c void f(void) { static int x = 0; x += 10; printf("%d ", x); } int main(void) { for (int i = 0; i < 3; i++) f(); }
- What is printed? c int global = 1; void modify(void) { int global = 2; global++; } int main(void) { modify(); printf("%d", global); }
- What is printed? c #include <stdio.h> int x; // tentative definition, file scope int x; // another tentative definition, same file int…
- What is printed? c static int x = 5; void f(void); void f(void) { printf("%d", x); } int main(void) { f(); }
- What is printed? c int a = 2, b = 3, c = 4; int r = a + b c - a / b; printf("%d", r);