C++ Scope

In C++, scope decides where a variable can be seen and used in your program. A variable only exists inside the block of code where it is declared, so understanding scope helps you avoid confusing errors and write cleaner functions. On this page you will learn about local scope, global scope, and block scope, and how they work together.

What is Scope?

Scope is the region of your program where a name (like a variable) is valid. When you declare a variable, it becomes available from that point until the end of the block it lives in. Outside that region, the name simply does not exist, and trying to use it causes a compile error.

Local Scope

A variable declared inside a function is called a local variable. It only exists while that function runs and cannot be reached from other functions. This keeps each function self-contained and prevents accidental interference between different parts of your code.

A local variable inside a function

#include <iostream>
using namespace std;

void greet() {
  string name = "Maya"; // local to greet()
  cout << "Hello, " << name << "!" << endl;
}

int main() {
  greet();
  // cout << name; // Error: name is not visible here
  return 0;
}

Global Scope

A variable declared outside of all functions has global scope. It can be used by every function in the file. Global variables are handy for values shared everywhere, but too many of them make code hard to follow, so use them sparingly.

A global variable seen by every function

#include <iostream>
using namespace std;

int counter = 0; // global variable

void increase() {
  counter++; // can access the global
}

int main() {
  increase();
  increase();
  cout << "Counter is " << counter << endl; // prints 2
  return 0;
}

Block Scope

Any pair of curly braces { } creates a new block, and variables declared inside it live only within that block. This is common in loops and if statements. Notice how a variable declared inside a for loop cannot be used after the loop ends.

Block scope inside a loop

#include <iostream>
using namespace std;

int main() {
  for (int i = 0; i < 3; i++) {
    int square = i * i; // exists only inside the loop body
    cout << square << " ";
  }
  // cout << i;      // Error: i is out of scope
  // cout << square; // Error: square is out of scope
  return 0;
}
Note: If a local variable has the same name as a global variable, the local one wins inside its scope. You can still reach the global one using the scope resolution operator, like ::counter.
Scope TypeWhere DeclaredWhere Usable
LocalInside a functionOnly in that function
BlockInside { } bracesOnly in that block
GlobalOutside all functionsAnywhere in the file

Exercise: C++ Scope

What is the scope of a variable declared in a for loop's init statement, like for(int i=0; ...)?