Search code examples
c++while-loopcomma-operator

What is the use of "," in while loop condition c++?


string command;
string bookName;
while (cin >> command, command != "END")
{...}

Here in while loop's condition, there is a comma. I know that multiple conditions can be added using && or ||.

But why use ,?

Is there any certain benefits? Can you please explain the usage and syntax?


Solution

  • It's the comma operator, also known as the "evaluate and forget" operator. The effect of a, b is:

    1. Evaluate a, including any side effects
    2. Discard its value (i.e. do nothing with it)
    3. Evaluate b
    4. Use the result of b as the result of the entire expression a, b

    The author of the loop wanted to express the following:

    Read command from cin, and then enter the loop body unless command is equal to "END"

    However, they would have been better off using && instead of , here, because cin >> command can fail (i.e. if the end of input is reached before the word END is found). In such case, the condition with , will not do what was intended (it will likely loop forever, as command will never receive the value END), while the condition with && would do the right thing (terminate).