Sidney
Sidney

Reputation: 708

Are there any languages where "A == B == C" works where A, B, and C are all non-boolean types?

Without thinking in C# I tried to compare three objects. It failed, and explained why [since (typeof("A == B") == bool) and (typeof(C) != bool) it was an invalid comparison]. Do any languages support short circuiting logic like this?

Upvotes: 3

Views: 79

Answers (1)

Espen
Espen

Reputation: 2576

There are several languages that let you do multiple conditionals like this. But the first I could think of was Python

Example:

a = 5
b = 5
c = 5
if(a == b == c):
    print "yes"
else:
    print "no"

Will print "yes" in the console.

It works with other types as well, like this:

a = ["A",1]
b = ["A",1]
c = ["A",1]
d = ["A",1]
if(a == b == c == d):
    print "YES"
else:
    print "NO"

Now the reason for C# (And other C like languages) doesn't support this is that they evaluate comparison expressions down to a true / false, so what your compiler sees when you do (5 == 5 == 5) is ((5 == 5) == 5) which yields: (true == 5) which invalid since you cannot compare a Boolean to an integer, you could actually write (a == b == c) if c is a Boolean, so (5 == 5 == true) would work.

Upvotes: 1

Related Questions