ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
int x = 10;
void f(void) {
    int x = 20;
    {
        int x = 30;
        printf("%d ", x);
    }
    printf("%d ", x);
}
int main(void) {
    f();
    printf("%d", x);
}
  1. A. 30 20 10
  2. B. 10 20 30
  3. C. 30 10 20
  4. D. 20 30 10

Correct answer: A. 30 20 10

Each block introduces its own scope, and an inner declaration of the same name shadows the outer one only within that inner block. The innermost block's x=30 is used inside it; once that block ends, f()'s own x=20 is visible again; main()'s own global x=10 is untouched throughout, since f() never modifies the global (it only ever shadows it).

More C Programming questions

Exams that ask this topic