Enums - probably an old subject

inout inout at gmail.com
Thu Nov 21 09:19:16 PST 2013


On Thursday, 21 November 2013 at 07:22:39 UTC, Steve Teale wrote:
> import std.stdio;
>
> enum Intention
> {
>    EVIL,
>    NEUTRAL,
>    GOOD,
>    SAINTLY
> }
>
> void foo(Intention rth)
> {
>    if (rth == EVIL)
>       writeln("Road to hell");
> }
>
>
> void main()
> {
>    foo(EVIL);
> }
>
>
> Why does the compiler complain in both places about EVIL. Can 
> it not work out which EVIL I mean? There's only one choice.

Because of the follwoing:

import foo.bar;

enum Intention
{
   EVIL,
   NEUTRAL,
   GOOD,
   SAINTLY
}

void foo(Intention rth)
{
...
}

void main()
{
   // imagine that this works
   foo(EVIL);
}

module foo.bar;

// someone else adds this later
enum OtherIntention
{
   EVIL,
   NEUTRAL,
   GOOD,
   SAINTLY
}

BOOM! Code no longer compiles.

As a rule, the code that compiles and works should preserve its 
behavior when new code is added, so this is prohibited.

Also please post to D.learn


More information about the Digitalmars-d mailing list