if(bool = x) does not give a boolean result

bearophile bearophileHUGS at lycos.com
Fri May 7 10:29:05 PDT 2010


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


More information about the Digitalmars-d-learn mailing list