Search code examples
c++curly-bracescurly-brackets

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


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!


Solution

  • 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!