iterate over enum name:value pairs

bearophile bearophileHUGS at lycos.com
Sun Dec 8 16:40:46 PST 2013


Jay Norwood:

>     struct Suit {string nm; int val; int val2; string shortNm;};

You have missed my suggestions above regarding the struct :-)

Look at this:


void main() {
     int x;
     struct Foo1 {
         int bar1() { return x; }
     }
     pragma(msg, Foo1.sizeof);
     static struct Foo2 {
         // this gives an error
         int bar2() { return x; }
     }
     pragma(msg, Foo2.sizeof);
}


bar2() gives an error because it can't access x. If you comment 
out the bar2 line, the output is:

4u
1u

Usually you don't want your struct defined inside a function to 
contain a pointer to the enclosing function.



>
>     static Suit[5] suits =  [
> 		{"spades",1,6,"spd"},
> 		{"hearts",4,10,"hrt"},
> 		{"hearts2",4,10,"hrt2"},
> 		{"diamonds",10,16,"dmd"},
> 		{"clubs",11,17,"clb"}
> 		];

Unless you have to mutate the contents of a variable, like your 
suits, define it const or immutable:

       static immutable Suit[5] suits =  [
	       {"spades",1,6,"spd"},
               ...
              ];

Generally in D add const/immutable to all variables that you 
don't need to mutate, if/where you can.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list