Equality operator chaining?
bearophile
bearophileHUGS at lycos.com
Sun Nov 10 10:45:14 PST 2013
Few days ago I have suggested a small language enhancement:
http://d.puremagic.com/issues/show_bug.cgi?id=11410
In Python this code is allowed:
>>> x = 3
>>> y = 4
>>> z = 5
>>> x < y < z
True
It is compilable in C too:
int main() {
int x = 3;
int y = 4;
int z = 5;
int b = x < y < z;
return 0;
}
But GCC tells us with a warning that code doesn't work as
expected by a Python programmer:
test.c:5:15: warning: comparisons like 'X<=Y<=Z' do not have
their mathematical meaning [-Wparentheses]
int b = x < y < z;
So D disallows that code, giving:
test.d(5): Error: semicolon expected, not '<'
test.d(5): Error: found '<' instead of statement
- - - - - - - - - - - - - -
GCC accepts this code:
int main() {
int x = 4;
int y = 4;
int z = 4;
int b = x == y == z;
return 0;
}
With a warning:
test.c:5:15: warning: suggest parentheses around comparison in
operand of '=='
[-Wparentheses]
int b = x == y == z;
While DMD refuses that code:
test.d(5): Error: semicolon expected, not '=='
test.d(5): Error: found '==' instead of statement
In D I find several situations where a chained equality is handy:
if (n == foo(n) == bar(n) && ...
It avoids code like this, that needs an auxiliary variable:
aux = foo(n);
if (n == aux && aux == bar(n) && ...
Is this idea going to cause troubles with operator overloading or
something else? Do you like it? Is it important enough?
Bye,
bearophile
More information about the Digitalmars-d
mailing list