Ixion Chowdhury
Ixion Chowdhury

Reputation: 156

Isn't this an error in the book The C++ Programming Language(4 ed)?

I was recently going through this thick manual to have a clearer and deeper understanding of C++ and I stumbled across this piece of code in Section 8.4.2 (page 222) which I think is an error.

Here is the code:

enum Traffic_light { red, yellow, green };
enum Warning { green, yellow, orange, red }; // fire alert levels

// error : two definitions of yellow (to the same value)
// error : two definitions of red (to different values)

Warning a1 = 7; // error : no int->Warning conversion
int a2 = green; // OK: green is in scope and converts to int
int a3 = Warning::green; // OK: War ning->int conversion
Warning a4 = Warning::green; // OK

void f(Traffic_light x)
{
    if (x == 9) { /* ... */ } // OK (but Traffic_light doesn’t have a 9)
    if (x == red) { /* ... */ } // error : two reds in scope
    if (x == Warning::red) { /* ... */ } // OK (Ouch!)
    if (x == Traffic_light::red) { /* ... */ } // OK
}

Shouldn't there be a third line error comment like this:

// error : two definitions of green (two different values)

The rest of the code seems to assume that green exists in only one enum scope.

Upvotes: 4

Views: 115

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

You are right, and we can see this by simply compiling the code (or trying to!).

It's not mentioned in the errata, either.

Upvotes: 2

Related Questions