1
int a,b;
while (cin>>a>>b, a)
{
    some task;
}

I don't understand the while loop condition here. I understand that I am taking input of a and b. But what is with the , a part?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 3
    https://stackoverflow.com/questions/52550/what-does-the-comma-operator-do – Retired Ninja Nov 04 '20 at 03:32
  • 2
    Comma operator. What is to the left of the comma is evaluated, but the value discarded and the value for the expression is the value to the right of the comma. So you are reading `a` and `b`, the stream-state is discarded and the loop is controlled by the value of `a`. – David C. Rankin Nov 04 '20 at 03:35
  • 2
    This program has undefined behavior if the stream does not contain a value that can be parsed as an integer. It should be: `while (cin >> a >> b && a)` – paddy Nov 04 '20 at 03:41
  • Your while loop enters integers `a` and `b` on each iteration and if `a` is not zero then loops body is executed, then again `a` and `b` entered, `a` checked to be non zero, etc. Loop finishes/exits immediately when first time zero `a` is entered. – Arty Nov 04 '20 at 03:50
  • 2
    @paddy it is not undefined behavior since C++11, where the output of `operator>>` for integral types is now well-defined as 0 for a failed read. – Remy Lebeau Nov 04 '20 at 05:33

0 Answers0