Diffrientiation in outputs depending on the ommition of curly braces in for loops (c++)

83 views Asked by At

I have been going through the c++ primer book as suggested by a reference guide on this site and I noticed the author omits curly braces for the for loop.I checked other websites and the braces are supposed to be put in usually. There is a different output when putting the curly braces and omitting it.The code is below

int sum = 0;
for (int val = 1; val <= 10; ++val)
    sum += val;  
    std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;

// This pair of code prints the std::cout once
for (int val = 50; val <=100;++val)
    sum += val;
    std::cout << "Sum of 50 to 100 inclusive is " << sum << std::endl;

// -------------------------------------------------------------------------
for (int val = 1; val <= 10; ++val) {
    sum += val;  
    std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
}

// This pair of code prints the std::cout multiple times
for (int val = 50; val <=100;++val) {
    sum += val;
    std::cout << "Sum of 50 to 100 inclusive is " << sum << std::endl;
}

I would appreciate if anyone could explain the difference in outputs. Thanks in advance!

2

There are 2 answers

4
EDD On BEST ANSWER

With curly braces everything in the braces get executed by the for loop

for (...;...;...)
{
     // I get executed in the for loop!
     // I get executed in the for loop too!
}
// I don't get executed in the for loop!

However without curly braces it only executes the statement directly after it:

for (...;...;...)
     // I get executed in the for loop!
// I don't get executed in the for loop!
// I don't get executed in the for loop either!
0
Vlad from Moscow On

The for statement in particularly is defined the following way

for ( for-init-statement conditionopt; expressionopt) statement
                                                      ^^^^^^^^^

where the statement can be any statement including the compound statement

compound-statement:
    { statement-seqopt}

Thus in this example of a for statement

for (int val = 1; val <= 10; ++val)
sum += val; 

the statement is

sum += val; 

While in this example of a for statement

for (int val = 1; val <= 10; ++val) {
sum += val;  
std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
}

the statement is

{
sum += val;  
std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
}