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?
It's the comma operator, also known as the "evaluate and forget" operator. The effect of a, b is:
a, including any side effectsb
b as the result of the entire expression a, b
The author of the loop wanted to express the following:
Read
commandfromcin, and then enter the loop body unlesscommandis 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With