theakhilarya's blog

By theakhilarya, history, 3 years ago, In English

I want to compare four integers and see whether they are equal or not. So wrote the following,

int a = 1, b = 2, c = 3, d = 4;
if (a != b != c != d)
{
    //do something
}

This apparently shows no error. But, in fact, giving the wrong answer. Can someone explain this, please?

  • Vote: I like it
  • -8
  • Vote: I do not like it

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

you have to compare each pair, there's no shortcut:

if (a != b && b != c && c != d) {
    // ...
}

or, you can also throw these variable in an std::set and check if the size is 4

  • »
    »
    3 years ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    also, your code compiles because it's equal to

    if (((a != b) != c) != d) {
        // ...
    }
    

    or something similar