Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement without the inner scope?

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?
}
like image 538
NPS Avatar asked Dec 25 '22 20:12

NPS


1 Answers

N4140 [stmt.select]/1 reads:

The substatement in a selection-statement (each substatement, in the else form of the if 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
}
like image 101
Anton Savin Avatar answered Jan 12 '23 09:01

Anton Savin