Ch3.2: Compound

Compound Statement

A compound statement is a group of statements enclosed in braces:

{
    ;
    ;
}

The braces { } make several statements behave as one single statement.

Local Variables Inside a Compound Statement

A compound statement also creates a scope. Variables declared inside the braces are destroyed when the closing } is reached.


{
    ::std::uint_least32_t v{};
    v = 5;   // OK: v exists here
}

v = 6;       // ERROR: v was destroyed at the }

After the block ends, v no longer exists.

Shadowing

If you declare a variable with the same name in an inner scope, it shadows the outer one:


::std::uint_least32_t v{1};

{
    ::std::uint_least32_t v{2}; // shadows the outer v
    // this v is different
}

Shadowing is legal, but often confusing. Compilers can warn you about this if you enable:

-Wshadow

We recommend always enabling this warning.

Key takeaways