ProgrammingHardIBM · Deloitte pattern

What is printed?

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

Correct answer: B. 30 20 10

The innermost block's x=30 shadows foo's x=20, which shadows the global x=10. Each printf uses the innermost x visible at that point: 30 inside the nested block, 20 after it ends (back in foo's scope), 10 in main (the global).

More C Programming questions

Exams that ask this topic