+ 2
C++ // if function with char variables
Why is this code not returning "No"? #include <iostream> using namespace std; int main () { char answer; answer = 'a'; if(answer = 'y') { cout << "Yes" << endl; } else { cout << "No" << endl; } return 0; }
2 Answers
+ 1
That's because you used = operator instead of == operator. When you want to compare, you use ==, when you want to assign, you use =. In you program you used if(answer = 'y'), so 'y' was assigned to variable answer. This assignment returned ASCII value of 'y', which is somewhere around 120. It is not 0, so that expression is evaluated as true, that is why your program prints "Yes".
+ 1
Thanks a lot Daniel!