What happens if a local variable and a global variable have the same name in C++?

Options

  • A. The program always gives a compilation error
  • B. The local variable generally hides the global variable within its scope
  • C. The global variable is automatically deleted
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

B. The local variable generally hides the global variable within its scope

Detailed Explanation

Answer: (B) The local variable generally hides the global variable within its scope

C++ allows a local variable to have the same name as a global variable. When this happens, the local variable hides the global variable within the local scope.

For example, if both global and local variables are named x, an unqualified use of x inside the local block refers to the local variable.

The global variable can still be accessed using the scope resolution operator :: when appropriate.