0

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!

Bill Lynch
  • 76,897
  • 15
  • 123
  • 168
  • 1
    _"... and I noticed the author omits curly braces for the for loop."_ Throw that book into your bin. Immediately. – πάντα ῥεῖ Jan 18 '16 at 21:29
  • The best advice is to **always** use curly braces with your for/while/if statements. Omitting braces is legacy syntax that should be avoided, IMO. See also https://www.google.com/search?q=heartbleed – Ryan Bemrose Jan 18 '16 at 21:43
  • @πάνταῥεῖ Lol I already stopped using another book for 'promoting bad practices'. –  Jan 18 '16 at 21:54
  • @RyanBemrose Thanks for the advice! –  Jan 18 '16 at 21:55

2 Answers2

3

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;
}
Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303
0

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!
Mukesh Ingham
  • 1,401
  • 8
  • 23