Assuming the compiler accepts the legacy C-style declarations shown below and…
2015
Assuming the compiler accepts the legacy C-style declarations shown below and printf is available, what does the following program print?
main()
{
inc(); inc(); inc();
}
inc()
{
static int x;
printf("%d", ++x);
}Answer: B. prints 123 — ConceptA block-scope static variable has static storage duration: it is initialized only once, to zero when no initializer is supplied, and retains its stored…
- A.
prints 012
- B.
prints 123
- C.
prints 3 consecutive, but unpredictable numbers
- D.
prints 111
Attempted by 840 students.
Show answer & explanation
Correct answer: B
Concept
A block-scope static variable has static storage duration: it is initialized only once, to zero when no initializer is supplied, and retains its stored value across function calls. A prefix increment changes that stored value before the surrounding expression uses it.
Application
Before the first call to inc(), the static variable x has its default initial value 0.
On the first call, ++x changes x from 0 to 1, and printf displays 1.
On the second call, x still stores 1; ++x changes it to 2, and printf displays 2.
On the third call, x still stores 2; ++x changes it to 3, and printf displays 3.
Cross-check
The trace preserves x between calls and produces the sequence 1, 2, 3. The legacy-declaration assumption affects whether the source is accepted, not this state trace after acceptance.
Result
With the stated legacy-acceptance assumption, the program prints 123 without spaces.
Explore the full course: Iocl Engineers Officers Grade A Paper 2