0
Question about if else statements
I was experimenting with some c++ when I came across this problem: char firstLetter; cin >> firstLetter; if (firstLetter == 'q' || 'Q') { cout << "blah blah bkkahhahkdk"; } else { cout << "more blah blah blakkrhfb"; } return 0; No matter what letter I put in, the code will always execute the first cout. Now I understand that the problem lies in the "if (firstLetter == 'q' || 'Q')" statement; I did that on purpose. The problem is I don't know exactly why it doesn't work. Any explanations appreciated.
5 Answers
+ 3
cause second argument is always "true" . Correct is :
char a;
cin>>a;
If(a=='q' || a=='Q'){
// some code...
}
+ 1
you need to do if(firstLetter == 'q' || firstLetter == 'Q')
+ 1
In statement for - if(firstLetter == 'q' || 'Q'), as per C operator precedence || will be executed first. As value of 'q/Q' is not zero. Right side q' || 'Q' is always evaluated as '1-True'.
This can be fixed by solution given by Anton.
Hope this helps....!!!
0
Electron_03 & Anton Bohler I understand already how to fix it, I'm just curious on why the concept of using this doesn't work.
0
when writing 'Q' in the if statment the compiler/interpreter converts 'Q' to a boolean
since 'Q' is true (i don't know what character/s are false) the if-statment will always be true.
you can't write it like that because the conditions are looked at seperatly