debio
debio

Reputation: 155

Problem with Book Example

Is it just me, or is there a problem with page 68 of "The D Programming Language" ? On this page, the author discusses D's syntax of if-else statements and how they nest. He first presents this example:

if(a == b)
    if(b == c)
        writeln("all are equal!");
    else
        writeln("a is different from b. Or is that so?");

He then points out that the else will bind to the second if. He then says that, to get the else to bind to the first if, one should use braces like so:

if(a == b) {
    if(b == c)
        writeln("all are equal!");
    else
        writeln("a is different from b. Or is that so?");
}

Am I missing the point completely, or would you have to do this:

if(a == b) {
    if(b == c)
        writeln("all are equal!");
}
else
    writeln("a is different from b. Or is that so?");

Upvotes: 5

Views: 207

Answers (2)

Baxissimo
Baxissimo

Reputation: 2619

You are correct. The example code is wrong. But the text in the book is correct: "If you instead want to bind the else to the first if, "buffer" the second if with a pair of braces". But the code doesn't show "buffering" just the second if.

Upvotes: 2

Jonathan M Davis
Jonathan M Davis

Reputation: 38287

It is indeed an error. The errata for TDPL can be found here: http://www.erdani.com/tdpl/errata/index.php?title=Main_Page

Upvotes: 5

Related Questions