Getting the number of elements in an enumerated type.

Stephen Carlson scc at rlgvax.UUCP
Sat Oct 27 10:01:40 AEST 1990


In article <6837 at castle.ed.ac.uk> elee24 at 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 at rlgvax.opcr.icl.com    | 11490 Commerce Park Drive
..!uunet!rlgvax!scc        | Reston, VA  22091



More information about the Comp.lang.c mailing list