AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Easycscope

~60s

A local that hides a global

What does this C program print?

#include <stdio.h>

int x = 10;

void f(void) {
    int x = 20;
    x = x + 1;
    printf("%d ", x);
}

int main(void) {
    f();
    printf("%d", x);
    return 0;
}
Show the answer and the worked solution

Correct answer: C.

21 10

Worked solution

  1. The declaration int x = 20 inside f introduces a new local variable that hides the global for the whole of that function.
  2. x = x + 1 therefore raises the local to 21, and f prints 21.
  3. The global x was never touched, so main prints 10 and the whole output is 21 10.

Answer: 21 10.

The idea

An inner declaration shadows an outer one of the same name for the rest of that block. Nothing links the two variables, so changes to one leave the other exactly as it was.

Shortcut. The local int x = 20 hides the global for the whole of f, so f prints 21 and main's global 10 is untouched.

Common trap. "21 21" assumes the assignment inside f reaches the global x; it changes only the local copy that shadows it.

A local that hides a global — Aptitude Question

A local that hides a global: What does this C program print? Answer and worked solution on CodeKairo.

Question

What does this C program print?

#include <stdio.h>

int x = 10;

void f(void) {
    int x = 20;
    x = x + 1;
    printf("%d ", x);
}

int main(void) {
    f();
    printf("%d", x);
    return 0;
}

Options

  1. 11 10
  2. 11 11
  3. 21 10
  4. 21 21
Show the answer and the worked solution

Correct answer: C. 21 10

Worked solution

  1. The declaration int x = 20 inside f introduces a new local variable that hides the global for the whole of that function.
  2. x = x + 1 therefore raises the local to 21, and f prints 21.
  3. The global x was never touched, so main prints 10 and the whole output is 21 10.

Answer: 21 10.

The idea

An inner declaration shadows an outer one of the same name for the rest of that block. Nothing links the two variables, so changes to one leave the other exactly as it was.

Shortcut. The local int x = 20 hides the global for the whole of f, so f prints 21 and main's global 10 is untouched.

Common trap. "21 21" assumes the assignment inside f reaches the global x; it changes only the local copy that shadows it.

All Programming Fundamentals questions · placement mock tests