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(); }
  1. A. 100
  2. B. 0
  3. C. Compile-time error: extern cannot be used inside a function body
  4. 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

Exams that ask this topic