Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

while-loop

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?

like image 771
alamin Avatar asked Nov 30 '22 15:11

alamin


1 Answers

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

like image 198
Angew is no longer proud of SO Avatar answered Dec 06 '22 14:12

Angew is no longer proud of SO