Path: utzoo!attcan!uunet!rlgvax!scc From: scc@rlgvax.UUCP (Stephen Carlson) Newsgroups: comp.lang.c Subject: Re: Getting the number of elements in an enumerated type. Message-ID: <1358@rlgvax.UUCP> Date: 27 Oct 90 00:01:40 GMT References: <6837@castle.ed.ac.uk> Reply-To: scc@rlgvax.OPCR.ICL.COM (Stephen Carlson) Organization: ICL North America, OFFICEPOWER Products Center, Reston, VA Lines: 35 In article <6837@castle.ed.ac.uk> elee24@castle.ed.ac.uk (H Bruce) writes: >Can you automatically get the number of elements in an enumerated type ? No, not automatically. But if you define your enums without explicit values, just add an extra element to the end like this: /* 0 1 2 */ enum foo { bar, baz, max_foo }; Here, max_foo will have the integer value of the number of elements (not counting max_foo) in the enum. There are three elements in this enum, the two real ones and the third which holds the number of elements. The elegance of C's zero-based system really shines through in this example. On a non-fascist compiler (one that does not complain about pointer arithmetic with enums), you can do: int a[max_foo]; enum foo ix; for (ix = bar; ix < max_foo; ix++) a[ix] = 0; if (some_condition()) a[bar] = 2; This approach works well with using enums to index arrays. I hope this helps. -- Stephen Carlson | ICL OFFICEPOWER Center scc@rlgvax.opcr.icl.com | 11490 Commerce Park Drive ..!uunet!rlgvax!scc | Reston, VA 22091