What is the scope of a variable declared inside an if block in C++?
Options
- A. Whole program
- B. Only within that block
- C. Only inside main()
- D. More than one of the above
- E. None of the above
Quiz Practice:
B. Only within that block
Answer: (B) Only within that block
Variables declared inside a block such as an if statement have block scope.
For example:
if (x > 0) { int y = 10; }
The variable y exists within that block and cannot be directly used after the closing }.
This rule also applies to variables declared inside other blocks such as loops and nested blocks.