Reputation: 11
Why this code does not print awesome
#include <iostream>
using namespace std;
int main() {
while (1, 0) {
cout << "awesome\n";
}
return 0;
}
But this code prints awesome Infinite times
#include <iostream>
using namespace std;
int main() {
while (0, 1) {
cout << "awesome\n";
}
return 0;
}
I'm using g++ compiler
Upvotes: 1
Views: 83
Reputation: 39
because the while loop doesn't care about the first part of your expression.
#include<iostream>
using namespace std;
int main(){
while(0 <- ,1){cout<<"awesome\n";}
return 0;
}
This part will be ignored. Compile your code with -Wall.
If this part will be ignored, the code is false in the first example and true in the last example.
Upvotes: 2
Reputation: 2371
Because you're using the comma operator (Does while loop have two Arguments?) which evaluates the first operand (before comma) and returns the second.
Which means that in your first loop, you're doing while(0)
, and 0 is evaluated to false
(immediatly ends). And in your second your doing while(1)
, and 1 is evaluated to true
(infinite loop).
Upvotes: 1