/* ** $Id: enum.c 802 2008-03-01 19:26:43Z phf $ ** ** Basic enumeration types, not much to say about these, ** except for "Please use them if appropriate." I guess? */ #include #include #define ONE 1 #define TWO 2 const int one = 1; const int two = 2; enum bla { eins = 1, zwei = 2 }; // explicit values enum xyz { a, b, c }; // implicit values starting at 0 enum pop { q=12, o, f, p=12, t, m }; // strange but allowed... int x = ONE; // works since textual substitution by preprocessor //int y = one; // doesn't work since const int is not really const... :-/ int z = eins; // works, so enum is a good replacement for #define int main(void) { // just to show off the values, check the last one especially! printf( "%d %d %d\n", ONE, one, eins ); printf( "%d %d %d\n", a, b, c ); printf( "%d %d %d %d %d %d\n", q, o, f, p, t, m); // we can use enums as type for variables, but unlike in Pascal // we don't get much help from the compiler restricting possible // values we can assign :-/ however, using an enum type still is // good style and documents your intention of only allowing some // values but not others; you can also use an assertion to make // sure of course enum bla x; // aside: shadows global x... x = eins; // should work, that's how enum bla is defined x = zwei; // again x = 0xAFFE; // shouldn't be valid, but it's not checked... :-/ // assignment from enums to ints are allowed, and sadly the // reverse is true as well... :-/ int z; // aside: shadows global z... z = x; // good x = z; // not so good, again no range check return EXIT_SUCCESS; }