What is special about the lifetime of a static local variable in C++?

Options

  • A. It is destroyed immediately after every statement
  • B. It retains its value between function calls
  • C. It can only be declared globally
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

B. It retains its value between function calls

Detailed Explanation

Answer: (B) It retains its value between function calls

A static local variable has local scope, but its lifetime extends for the duration of the program.

For example:

void count() { static int x = 0; x++; }

Each time the function is called, the same static variable is used and its previous value is retained.

This is an important distinction: scope tells where a variable can be accessed, while lifetime tells how long the variable exists.