Why does it break out of the loop?

Why does it break out of the for loop if I write a number that isn't equal to either 1, 2 or 3 (for example 4)? I understand why it breaks out of the loop when I write 1 2 3, but with other numbers? I don't get it.


1
2
3
4
5
6
7
8
9
10
    int op;
    int exitloop = 1;

    for (int i = 0; exitloop == 1; i++) {
        cout << "Something" << endl;
        cin >> op;
        if (op == 1, 2, 3) {
            exitloop = 0;
        }
    }
Because 2 and 3 are both true (in a world where 0 is false and everything else is true).

You might want to read up on the "comma operator" (which, incidentally, you are using but probably don't want to use).


Try
1
2
3
if (op == 1 || op == 2 || op == 3) {
            exitloop = 0;
}


or

1
2
3
if (op >= 1 && op <= 3) {
            exitloop = 0;
}


or
exitloop = !(op == 1 || op == 2 || op == 3);
Last edited on
if (op == 1, 2, 3)
This use of the comma operator is misleading.
https://en.wikipedia.org/wiki/Comma_operator

It evaluates each thing from left to right, then returns the right-most value.
So in your case, it's evaluating op == 1, then evaluating the expression 2 (note: not op == 2), then evaluating the expression 3, and then it returns 3, which evaluates to true for an if condition (any non-zero value evaluates to bool true).

If you meant to say ||, then use || (logical OR). Each statement must also be independent.
1
2
3
4
if (op == 1 || op == 2 || op == 3)
{
    exitLoop = 0;
}


Also, the naming of "exitLoop" seems to be the opposite of what its purpose is in your code.
op == 1, 2, 3
What is the value of op == 1? true or false

What is the value of false, 2, 3? What does the comma-operator do?

http://www.cplusplus.com/doc/tutorial/operators/ says:
When the set of expressions has to be evaluated for a value, only the right-most expression is considered.

That is, if ( false, 2, 3 ) has same resolution as if ( 3 ).

You want to break out when op is 1 or op is 2 or op is 3? Lets write that:
op == 1 || op == 2 || op == 3
Last edited on
Thank you very much everyone! I will definitely read more about the comma operator.
Topic archived. No new replies allowed.