Reputation:
How does comma operator if it is used in a 'for loop' for writing multiple control statements? i tried
#include <iostream>
using namespace std;
int main() {
for (int x = 0, y = 0; x < 3, y < 4; ++x, ++y) {
cout << x << " " << y << endl;
}
return 0;
}
and it seems like only the last expression is evaluated. Ty
Upvotes: 1
Views: 249
Reputation: 172964
This is how comma operator works. Its 1st operand x < 3
is evaluated, then the result is discarded; then the 2nd operand y < 4
is evaluated and the value is returned as the return value of the comma operator. x < 3
has not any effects here.
You might want to use operator&&
or operator||
for this case, e.g. x < 3 && y < 4
or x < 3 || y < 4
based on your intent.
Upvotes: 5