Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boolean expressions, why just two terms?

Given that it's valid to write

a = b = c = 2;

It would also be nice, rather than

bool allTwo = a == 2 && b == 2 && c == 2;

to instead write

bool allTwo = a == b == c == 2;

But I can't since a == b evaluates to a boolean which can't then be compared to an integer.

Is there a language-design reason it has been implemented this way?

like image 868
Ed Guiness Avatar asked Nov 30 '22 10:11

Ed Guiness


2 Answers

The type of the expression a == b is boolean, so you would either have to break a rule that an expression means the same thing whatever its context, or have n-ary == operators so that a == b == c is parsed as (== a b c) rather than (== (== a b) c). Which then means you need to have (a == b) == c to compare the boolean c to the result of (a == b), which is OK, but not the simple C style of grammar which C# is in the tradition of.

like image 180
Pete Kirkham Avatar answered Dec 02 '22 23:12

Pete Kirkham


Well, the expression c == 2 would return true, so then b would be being compared to true rather than 2.

Edit: It was most likely implemented this way as that's how C-style languages handle boolean expressions. They'd have to make a special exception for multiple terms and implement it differently whereas with the assignment operator it's more straightforward: the right most expression evaluates to a value that can logically be applied to the next expression in the chain. Seems the designers took the simple approach.

like image 26
Bob Avatar answered Dec 03 '22 00:12

Bob