Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop inside its own curly braces

People also ask

What loop is required for curly braces?

If the number of statements following the for/if is single you don't have to use curly braces. But if the number of statements is more than one, then you need to use curly braces.

Should curly braces appear on their own line?

We strongly recommend you format your curly brackets following Java conventions: Do not put a new line before an opening curly bracket. Always start a new line after an opening curly bracket. A closing curly bracket should always belong on a separate line, except for else statements.


Once upon a time, many moons ago, VS6 existed and was popular. It failed however to conform to a number of C++ standards; which was reasonable at the time as it was released just before (on the same year) the standard was officially released; it did however adhere to the draft of the standard as far as I'm aware.

One of the standards that changed between the draft and the official standard, was the lifetime of for loop variables created in the first section; leading to the following code failing to compile

{
    for (int i=0; i<1; ++i){}
    for (int i=0; i<2; ++i){}
}

because i was redefined by the second for loop.

While other compilers also suffered this bug; I highlight the VS6 one because it remained the only version of visual studio for a number of years after the release of the standard, but never released an update for this particular issue; meaning that it had a more significant impact.

A solution to this is to force the whole for loop into its own scope as you have shown.


{ and } will create a scope and if you define some variables in the scope you cannot access them from outside. But for already create that scope. So

{for(int i = 0; i < count; ++i){}} 

is the same as

for(int i = 0; i < count; ++i){}

but if you define something between them, there is a difference

{int a = 0; for(int i = 0; i < count; ++i){}}

In this example, a won't be accessible from outside scope.


In your particular example there is no reason for them.

Sometimes you could want to create a scope for a variable:

float average;
// ...

{
int sum = 0;
for (int i = 0; i < count; ++i)
{
   sum += v[i];
}
average = (float)sum / count;
}

// use average
// sum not in scope here

However I see this an anti-pattern. Usually if you find yourself in need of doing this then most likely the for should be its own function.


It's a block scope marked by {} braces. It is usually used to mark the area of automatic storage. In your case it doesn't seem to do anything as the for loop has its own scope in standard C++.