Understanding Scope in C++

In C++, the scope of a variable determines where it can be accessed in the code. Variables can have local or global scope depending on where they are declared.

Example: Local and Global Scope

#include <iostream>

int globalVar = 5; // global variable

void displayScope() {
    int localVar = 10; // local variable
    std::cout << "Local variable: " << localVar << std::endl;
}

int main() {
    displayScope();
    std::cout << "Global variable: " << globalVar << std::endl;
    // Uncommenting the next line would cause an error:
    // std::cout << localVar;
    return 0;
}
                    

Output:

Local variable: 10
Global variable: 5

Explanation: The variable localVar has local scope within displayScope(), meaning it cannot be accessed in main(). The globalVar, however, is declared outside any function, so it can be accessed in both displayScope() and main().

Key Takeaways

  • Local Scope: Variables declared inside a function or block are accessible only within that function or block.
  • Global Scope: Variables declared outside any function are accessible from any part of the code.
  • Best Practice: Avoid using global variables unless necessary, as they can make debugging harder.