jysning
jysning

Reputation: 21

order of conditions in while statement

#include <iostream>

int main()
{
   int number = 10;
   while (number <= 10, 0 <= number)
   {
     std::cout << number << std::endl;
     --number;
   }

   return 0;
}

The output prints 10...0. However with while (0 <= number, number <= 10) or while (0 <= number <= 10) the output prints 10...(infinite negative no.s). in fact, while (number <= 10, 0 <= number) seems to be the only one that prints 10...0.

Why is this so?

Upvotes: 2

Views: 46

Answers (2)

tsragravorogh
tsragravorogh

Reputation: 3153

To add to the previous answer, in order to achieve what you want to achieve in your loop using the comma operator, you can write your code like this:

#include <iostream>

int main()
{
   int number = 11;
   while (--number, 0 <= number)
   {
     std::cout << number << std::endl;
   }

   return 0;
}

What you are essentially doing is that at every step of the loop you are decrementing number by 1, and then checking to see if it's greater than or equal to 0. If it is then you will print its value, if not your loop will exit. So the first statement before the comma is just an execution and not part of the while loop's condition.

Upvotes: 1

dahiya_boy
dahiya_boy

Reputation: 9503

With the reference : Comma operator

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type); there is a sequence point between these evaluations.

That means,

  • when you do (0 <= number, number <= 10) operator only check number <= 10 condition and

  • when you do (number <= 10, 0 <= number) operator only check 0 <= number condition.

Hope now you have cleared why you getting different result.

To avoid such behavior I encourage you to use and operator (&&) that means

either do while (0 <= number && number <= 10) or do while (number <= 10 && 0 <= number)

Upvotes: 3

Related Questions