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

~90s

A static local variable

What does this C program print?

#include <stdio.h>

void f(void) {
    static int c = 0;
    int d = 0;
    c = c + 1;
    d = d + 1;
    printf("%d%d ", c, d);
}

int main(void) {
    f();
    f();
    f();
    return 0;
}
Show the answer and the worked solution

Correct answer: B.

11 21 31

Worked solution

  1. c is static, so its initialiser runs once and its value survives between calls: it becomes 1, then 2, then 3.
  2. d is an ordinary local, rebuilt and set to 0 at every call, so it is always 1 when printed.
  3. The three calls print 11, then 21, then 31, so the output is 11 21 31.

Answer: 11 21 31.

The idea

static inside a function changes the lifetime of the variable, not its scope: it lives for the whole program but is still invisible outside the function. That is why one digit climbs and the other does not.

Shortcut. d is rebuilt at every call, so every pair must end in 1, leaving "11 11 11" or "11 21 31"; the static c climbs, so 11 21 31.

Common trap. "11 11 11" treats static int c = 0 as running on every call; a static's initialiser runs once and its value persists.

A static local variable — Aptitude Question

A static local variable: What does this C program print? Answer and worked solution on CodeKairo.

Question

What does this C program print?

#include <stdio.h>

void f(void) {
    static int c = 0;
    int d = 0;
    c = c + 1;
    d = d + 1;
    printf("%d%d ", c, d);
}

int main(void) {
    f();
    f();
    f();
    return 0;
}

Options

  1. 11 11 11
  2. 11 21 31
  3. 11 22 33
  4. 13 13 13
Show the answer and the worked solution

Correct answer: B. 11 21 31

Worked solution

  1. c is static, so its initialiser runs once and its value survives between calls: it becomes 1, then 2, then 3.
  2. d is an ordinary local, rebuilt and set to 0 at every call, so it is always 1 when printed.
  3. The three calls print 11, then 21, then 31, so the output is 11 21 31.

Answer: 11 21 31.

The idea

static inside a function changes the lifetime of the variable, not its scope: it lives for the whole program but is still invisible outside the function. That is why one digit climbs and the other does not.

Shortcut. d is rebuilt at every call, so every pair must end in 1, leaving "11 11 11" or "11 21 31"; the static c climbs, so 11 21 31.

Common trap. "11 11 11" treats static int c = 0 as running on every call; a static's initialiser runs once and its value persists.

All Programming Fundamentals questions · placement mock tests