4
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?

P-Gn
  • 23,115
  • 9
  • 87
  • 104
alamin
  • 2,377
  • 1
  • 26
  • 31

1 Answers1

19

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).

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455