ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
int x = 100;
void f(void) {
extern int x;
printf("%d", x);
}
int main(void) { f(); }- A. 100
- B. 0
- C. Compile-time error: extern cannot be used inside a function body
- D. Undefined behaviour: x is not actually defined anywhere
Correct answer: A. 100
An extern declaration inside a function body is legal and simply tells the compiler to look for x's definition elsewhere (at file scope or another translation unit) rather than creating a new local variable. Since the file-scope int x = 100; already exists, f()'s extern int x; refers to that same global, printing 100.
More C Programming questions
- What is printed? c void f(void) { printf("%d ", x); } int x = 42; int main(void) { f(); }
- What is printed? c int x = 5; void modify(void) { x = 10; } int main(void) { int x = 20; modify(); printf("%d %d", x, ::x == 5); }
- What is printed? c static int helper(int x) { return x 2; } int main(void) { printf("%d", helper(5)); }
- What is printed? c void outer(void) { int x = 1; void inner(void) { printf("%d", x); } inner(); } int main(void) { outer(); }
- What happens at link time? c // file1.c static int counter = 0; void increment(void) { counter++; } c // file2.c (compiled and linked with…
- What is printed? c int x = 10; void foo(void) { int x = 20; { int x = 30; printf("%d ", x); } printf("%d ", x); } int main(void) { foo()…