Search code examples
c++loopswhile-loopcurly-braces

How is while loop working without a block of code, shouldn't it work only for curly braces?


I know that while loops have a body part with two curly braces { }. And I know that how while loops work. But when I was reading a book on C++, I found this code:

#include <iostream>
int main()
{
    int sum = 0, value = 0;
    // read until end-of-file, calculating a running total of all values read
    while (std::cin >> value)
        sum += value;   // equivalent to sum = sum + value
    std::cout << "Sum is: " << sum << std::endl;
    return 0;
}

But there are no curly braces { } and these code is working same as:

#include <iostream>
int main()
{
    int sum = 0, value = 0;
    // read until end-of-file, calculating a running total of all values read
    while (std::cin >> value){
        sum += value;   // equivalent to sum = sum + value
    }
    std::cout << "Sum is: " << sum << std::endl;
    return 0;
}

So how can it be possible when I omitted curly braces { } in While Loops and how does it work when it omit the curly braces in while loops?


Solution

  • The while's syntax is of the following form (simplified, check the link for more info):

    while ( condition ) statement
    

    Therefore, we need to supply it a statement after the condition part.

    Curly braces denote a compound statement (a.k.a block, block statement). It is a group of zero or more statements that is treated by the compiler as if it were a single statement.

    If you don't need a compound statement, you use an expression statements (a.k.a. one-liner). We terminate expression statements with a semicolon ;, while a block statement is terminated by closing curly brace.

    In the example we can get away with an expression statement:

    while (std::cin >> vInside curly braces wealue)
            sum += value; 
    

    In some cases, it is necessary to use curly braces to specify the flow of logic in program even if we use only expression statements. Also, some consider it to be a good practice to routinely use curly braces to explicitly denote boundaries every time.