C++ // if function with char variables | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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; }

28th Oct 2016, 3:57 PM
Daniel Stanciu
Daniel Stanciu - avatar
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".
28th Oct 2016, 4:25 PM
Daniel Oravec
Daniel Oravec - avatar
+ 1
Thanks a lot Daniel!
28th Oct 2016, 4:57 PM
Daniel Stanciu
Daniel Stanciu - avatar