-1

So, I'm running some code and I got it to work, but I have two if else statements.

Let's say

if (( a == 'b'||'c') && (d!=0)) {
    // do operation1;
} else if (( a == 'e'||'f') && (d!=0)) {
    // do operation2; 
}

operation 1 runs by default when my code was structured that way. What do I mean by default? If I tried typing the input 'e' or 'f' it would do operation 1 as if I had typed in 'b' or 'c' But then I tried something different.

if ((a == 'b') || (a == 'c') && (b != 0)) {
    // do operation 1;
} else if ((a == 'e') || (a == 'f') && (b!= 0)) {
    // do operation 2;
}

See NOW operation 1 and 2 are working as intended.

Why does this happen?

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
  • For language behavior questions you really should tag the language you're using. A lot of programming languages have `if-else` and many use at least something similar to the syntax you are showing. – lurker Jul 03 '18 at 20:31
  • My bad. The language is c++ – Dark_Firaga Jul 03 '18 at 21:03
  • BTW, this is a FAQ -- we have a language-agnostic meta-answer. – Charles Duffy Jul 03 '18 at 21:17
  • ...hmm, actually, I was thinking of [Why non-equality check of one variable against many values always returns true?](https://stackoverflow.com/questions/26337003/why-non-equality-check-of-one-variable-against-many-values-always-returns-true), but that's the **inequality** version. (See also [Canonical, language-agnostic question for if(var != “x” || var != “y” …)](https://meta.stackoverflow.com/questions/273262/canonical-language-agnostic-question-for-ifvar-x-var-y) on [meta]) – Charles Duffy Jul 03 '18 at 21:18
  • [How to test multiple variables against a value](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) is a Python-flavored duplicate. Still looking for a C/C++ one. – Charles Duffy Jul 03 '18 at 21:21
  • 1
    Your code is non-compilable. In C++ `if` requires a pair of `()` around its condition. Post something more meaningful. – AnT stands with Russia Jul 03 '18 at 21:25
  • What are example values of the variables `a` and `d`? – Code-Apprentice Jul 03 '18 at 21:32

1 Answers1

1
a == 'e'||'f' 

isn't doing what you think it's doing. 'f' as a boolean because its larger than the value 0, will always be considered true. Try the following.

a == 'e' || a == 'f'

The large difference between the two sets of code you have there, aren't the (brackets), it's the useage of '=='.

Nova Ardent
  • 161
  • 1
  • 16