0
do{
    cout << "your number"; cin >> z;


   if (z > 4){
    cout << "invalid answer" << endl;}
   else if (z == 4){
   cout << " no" << endl;}
   else {
   cout  <<"great!"   << endl; }
} while (z != 3, 2, 1);
}

In my oppinion it's: bring up "your number" until z is 3 or 2 or 1? What's wrong?'

  • 4
    `(z != 3, 2, 1)` is using comma operator. It evaluates the left hand expression and discards the results, then evaluates the right hand expression and returns the result. So your loop condition is equivalent to `while (1)`; – jrok Oct 14 '13 at 15:11
  • Look up the comma operator and operator precedence. Your `while` condition does not do what you think it does. – juanchopanza Oct 14 '13 at 15:11
  • 1
    Yet another candidate who failed to read through the tutorial until the comma operator... –  Oct 14 '13 at 15:11
  • `while (z != 3, 2, 1)` evaluates to: `while(1)` as the comma operator evaluates all the expressions and returns the last. – George Mitchell Oct 14 '13 at 15:13

2 Answers2

5
while (z != 3, 2, 1);

Your while condition is wrong, it should be:

while (z != 3 && z != 2 && z != 1);

If you use the commas, it will evaluate (calculate) all the expressions separated by them, and will use the last expression.

In this case

(z != 3, 2, 1)

It will evaluate z != 3, then 2 and finally will use 1, your while would look like this:

while(1);

Which is an infinite loop.

xorguy
  • 2,594
  • 1
  • 16
  • 14
0

The problem may falls on the while condition. The return value of your expression "z != 3, 2, 1" will evaluate to "1", which means true in C++. So there will be a infinite loop. Try to rewrite the cond. exp. like "z != 3 || z != 2 || z != 1".

Yuck
  • 49,664
  • 13
  • 105
  • 135
Toto
  • 1