Variables
Declaring Variables with Limited Scope
1. Variable declared in a wider scope
Here, c is declared in the surrounding scope (for example, inside main), so it remains alive until that scope ends.
This is not memory efficient in terms of scope, because c exists longer than needed.
2. Variable declared inside a block
In this approach, c is limited to this block.
Once the block finishes executing:
cgoes out of scopeits memory is released automatically
This is better because the variable exists only where it is needed.
3. Variable declared inside if (C++17)
This syntax was introduced in C++17.
cis created only for thisifstatementIt behaves exactly like the previous block-based approach
cis destroyed after theifstatement finishes
This is the cleanest and safest way when a variable is only needed for a condition.
4. Using declaration directly as a condition
Here:
eis declared and initialized inside the ifThe condition is true if
eis non-zeroeis destroyed after the if block
Again, the variable lives only as long as necessary.
If the expression in the if condition evaluates to 0, then if condition will not be executed, because expression has evaluated to false.