ProgrammingHardIBM · Deloitte pattern

What is printed?

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

Correct answer: D. 1 5 100

Each block introduces a new x that shadows the outer one within its own scope. The innermost block prints its x=1; once that block ends, the enclosing one sees its own x=5; main's x (the global, 100) is untouched by f's locals.

More C Programming questions

Exams that ask this topic