My C++ code is as follows:
#include <iostream>
using namespace std;
int main() {
int i = 0;
cout << (i=0) << endl;
if(i=0) {
i=1;
}
cout << i;
return 0;
}
Why is (i=0)
equal to 0?
My C++ code is as follows:
#include <iostream>
using namespace std;
int main() {
int i = 0;
cout << (i=0) << endl;
if(i=0) {
i=1;
}
cout << i;
return 0;
}
Why is (i=0)
equal to 0?
You have confused the assignment operator '=' with the equality operator '=='.
Thus, your if
statement if(i=0)
isn't checking whether i is equal to 0, it is assigning 0 to i. And since that assignment succeeded, the if
succeeded and so i was subsequently assigned to the value in the statement.
EDIT:
As per request: Why does "cout<<(i=0);" put out"0"?
cout<<(i=0)<<endl;
prints zero because once again, i=0
is an assignment statement, not a comparison statement. It is not comparing i to 0 then printing the result, it is assigning i to 0 and then printing i. Since i is 0, the character '0' gets printed.
If you put you condition to if(condition)
statements:
If value returned by condition is != 0, then statements are executed
If value returned by condition is == 0 then statements are not executed.
Assignment operator return the reference to value
So: If you put assignment operator to if, then the results of the assignment will be checked and i=0 return 0 so the statements won't be executed.
If you put your code on more lines and use a debugger you can answer your own question.
Should be obvious that the body of if(0) never runs.