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.

14th Aug 2019, 11:58 PM
Thomas Wald
Thomas Wald - avatar
5 odpowiedzi
+ 3
cause second argument is always "true" . Correct is : char a; cin>>a; If(a=='q' || a=='Q'){ // some code... }
15th Aug 2019, 12:14 AM
electron
electron - avatar
+ 1
you need to do if(firstLetter == 'q' || firstLetter == 'Q')
15th Aug 2019, 12:10 AM
Anton Böhler
Anton Böhler - avatar
+ 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....!!!
15th Aug 2019, 4:33 AM
Kuri
Kuri - avatar
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.
15th Aug 2019, 12:41 AM
Thomas Wald
Thomas Wald - avatar
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
15th Aug 2019, 1:23 AM
Anton Böhler
Anton Böhler - avatar