C++ Simple block scope


Example

The scope of a variable in a block { ... }, begins after declaration and ends at the end of the block. If there is nested block, the inner block can hide the scope of a variable which is declared in the outer block.

{
    int x = 100;
    //   ^
    //   Scope of `x` begins here
    //
}   // <- Scope of `x` ends here

If a nested block starts within an outer block, a new declared variable with the same name which is before in the outer class, hides the first one.

{
    int x = 100;

    {
        int x = 200;

        std::cout << x;  // <- Output is 200
    }

    std::cout << x;  // <- Output is 100
}