if(bool = x) does not give a boolean result
Johan Granberg
lijat.meREM at OVEgmail.com
Fri May 7 11:42:15 PDT 2010
bearophile wrote:
> Steven Schveighoffer:
>
>> I have code like this in dcollections:
>
> This is similar code that shows the same thing:
>
> import std.stdio;
> void main() {
> bool b = true;
> bool c;
> if (c = !b)
> writeln("****");
> }
>
>
>> Since when did bool = bool not give a bool result?
>
> I guess since Walter has decided to avoid in D the common bug present in C
> and C++ programs caused by using = instead of == inside an if(). For the
> exactly the same bug-avoidance purpose, Python too allows chained assigns:
> a = b = 10 but it refuses the assign in the if:
> if x = 10: ...
>
>
>> Do I have to write it out like this:
>> if((wasRemoved = !it.empty) == true)
>
> Yep. Or you can write it like this, also gaining readability as
> side-effect: wasRemoved = !it.empty
> if (wasRemoved) { ...
>
> In other situations you can write code like this in D:
> if (bool c = !b)
>
> A bit of less syntactic convenience is a price worth paying for a reduced
> bug-prone language that wants to keep the flavour of upwards compatibility
> to C that D wants.
>
>
>> I can understand for ints and strings and whatnot, but for booleans?
>
> My guess: that's a special case. Special cases kill languages (see C++),
> so better to have no exceptions. Less things to remember, simpler
> compiler, shorter books about D, less time to read the language.
>
> Bye,
> bearophile
This is all true but if this is how the feature should be defined I think
the error message should improve. Something along the lines
of, "Assignments not allowed as thruth values in conditional statments"
seems more clear.
More information about the Digitalmars-d-learn
mailing list