Afaik, every pair of { }
in the code creates a new scope. Even if it's used just for the sake of it without any if
, for
, function or other statement that demands it:
void myFun(void)
{
int a;
{
int local;
}
}
I started wondering - when the if
statement is written without using the braces (with 1-line body) does it still create a new scope?
voidmyFun(int a)
{
int b;
if (a == 1)
int tmp; // is this one local to if?
else
int tmp2; // or this one?
b = 2; // could I use tmp here?
}
N4140 [stmt.select]/1 reads:
The substatement in a selection-statement (each substatement, in the
else
form of theif
statement) implicitly defines a block scope
So, the code
if (a == 1)
int tmp; // is this one local to if?
else
int tmp2; // or this one?
is equivalent to
if (a == 1)
{
int tmp; // yes, this one is local to if
}
else
{
int tmp2; // and this one as well
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With