๐ŸŽ“ A1Learner
๐Ÿ”

C++ Scope

Scope is where a name can be used in a program. A name declared inside a block can be used only inside that block.

A variable inside a block

The level variable is declared inside a block. The print statement inside the block reads it.

#include <iostream>

int main() {
  {
    int level = 3;
    std::cout << level << std::endl;
  }
  return 0;
}

One name in two places

The outer value variable holds 10. A second value variable inside the block holds 20.

#include <iostream>

int main() {
  int value = 10;
  std::cout << value << std::endl;
  {
    int value = 20;
    std::cout << value << std::endl;
  }
  return 0;
}

A block variable used after its block

The hidden variable lives inside the block only. The print statement after the block uses that name, and the compiler refuses the program.

#include <iostream>

int main() {
  {
    int hidden = 7;
    std::cout << hidden << std::endl;
  }
  std::cout << hidden << std::endl;
  return 0;
}

Example

#include <iostream>

int main() {
  int score = 1;
  std::cout << "Outer: " << score << std::endl;
  {
    int score = 2;
    std::cout << "Inner: " << score << std::endl;
  }
  std::cout << "Outer: " << score << std::endl;
  return 0;
}

Key points

  • A block is a piece of code inside a pair of curly braces.
  • A variable declared in a block can be used only in that block.
  • The same name can be declared again in an inner block.
  • The inner declaration holds its own value while its block runs.
  • After the inner block ends, the outer value is in use again.
  • Using a block variable after its block fails to compile.

In this example, the outer score holds 1 and prints first. The inner block declares its own score with the value 2. After the block ends, the outer score prints again with its value 1.

Note

A name stops being usable at the closing brace of its block.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

Where can a variable declared inside a block be used?