C++ Scope

C++ Scope: Where Variables Exist

In C++, scope refers to the region of your code where a variable is accessible and can be used. Variables are not always available to every part of your program. Where you declare a variable determines its scope.

There are primarily two types of scope in C++: Local Scope and Global Scope.


1. Local Scope

A variable declared inside a function or a block of code (like an if statement or a for loop) has local scope.

Local Scope Example

#include <iostream>
using namespace std;

void myFunction() { // 'x' is a local variable int x = 10; cout << "Inside myFunction, x is: " << x << "\n"; }

int main() { myFunction();

// ERROR! 'x' is not declared in this scope. // cout << x;

return 0; }


2. Global Scope

A variable declared outside of all functions (usually at the top of your program) has global scope.

Global Scope Example

#include <iostream>
using namespace std;

// 'globalScore' is a global variable int globalScore = 100;

void updateScore() { globalScore += 50; // We can modify it here! }

int main() { cout << "Initial Score: " << globalScore << "\n"; updateScore(); cout << "Updated Score: " << globalScore << "\n";

return 0; }

Global vs. Local Variables with the Same Name

If a local variable has the same name as a global variable, the local variable takes precedence within its scope.

Naming Conflict Example

#include <iostream>
using namespace std;

int myNum = 10; // Global variable

int main() { int myNum = 50; // Local variable shadows the global one cout << "The value is: " << myNum << "\n"; // Prints 50 return 0; }


Best Practices

While global variables seem convenient, overusing them can lead to messy, hard-to-maintain code, as any part of the program can change their values unexpectedly. It is always better to use local variables and pass data to functions via parameters whenever possible!


Exercise

?

Where are global variables declared?