ProgrammingVery hardProduct company OA
What is printed?
What is printed?
int x = 5;
int f(void) {
int x = x + 1;
return x;
}
int main(void) { printf("%d", f()); }- A. 6, since the global x=5 is used on the right-hand side
- B. Undefined behavior: the local x is used (x + 1) to initialize itself before it has a determinate value
- C. 1, since x defaults to 0 before adding 1
- D. Compilation error: x used before declaration
Correct answer: B. Undefined behavior: the local x is used (x + 1) to initialize itself before it has a determinate value
The declaration `int x = x + 1;` introduces the new local x into scope starting at its own declarator, so the x on the right-hand side already refers to the NEW (not-yet-initialized) local x, not the outer global — reading its indeterminate value is undefined behavior, a classic self-initialization trap.
More C Programming questions
- What is printed? c int f(void) { static int x; return x++; } int main(void) { printf("%d %d %d", f(), f(), f()); }
- 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(); }