Comparison of three integer values

Is something like this possible?

if(a == b == c) 

or

 if((a== b) && (b == c)) 

- the only way?

or the coolest way to do this?

+4
source share
4 answers

In some languages ​​you can use this shorthand. For example, in Python, a == b == c roughly equivalent to the expression a == b and b == c , except that b is evaluated only once.

However, in Java and Javascript you cannot use the short version - you must write it, as in the second example. The first example will be approximately equivalent to the following:

 boolean temp = (a == b); if (temp == c) { // ... } 

This is not what you want. In Java, a == b == c does not even compile if c not logical.

+6
source

In java - we do not have the == shortcut operator. therefore, we end up making individual equalities.

But if you think that you will need functionality with the number of arguments changing , I would consider the possibility of implementing such a function. The following is sample code without handling exceptional conditions.

  public static boolean areTheyEqual(int... a) { int VALUE = a[0]; for(int i: a) { if(i!= VALUE) return false; } return true; } 
+1
source

In JavaScript, your safest bet is a === b && b === c . I always avoid using == in favor of === for my own sanity. Here is a more detailed explanation.

0
source

To get the maximum value of three numbers, one line method:

int max = (a> b & a> c)? a: ((b> a & b> c)? b: c);

-3
source

All Articles