F
Fred Zwarts
What is the recommended way to loop over all enum values of a certain enum type?
Consider the following definition:
typdef enum {A=2, B, C=5, D} E;
then
for (E x = A; x <= D; ++x) { ... }
does not work because
1) Some compilers complain that the ++ operator is not defined for enum types.
2) Other compilers complain that the test x<=D is always true.
3) Other compiler compile, but at run time illegal values are assigned to x.
I can, of course, define a ++ operator for E, but the code would probably consist
of a switch ... case construction, which is error prone, because modification of
the definition of E does not automatically adjust the cases within the ++ operator.
The problem that x<=D is always true could be solved by using a conditional break
at the end of the loop.
if (x==D) break;
Has someone found a simpler solution?
Fred.Zwarts.
Consider the following definition:
typdef enum {A=2, B, C=5, D} E;
then
for (E x = A; x <= D; ++x) { ... }
does not work because
1) Some compilers complain that the ++ operator is not defined for enum types.
2) Other compilers complain that the test x<=D is always true.
3) Other compiler compile, but at run time illegal values are assigned to x.
I can, of course, define a ++ operator for E, but the code would probably consist
of a switch ... case construction, which is error prone, because modification of
the definition of E does not automatically adjust the cases within the ++ operator.
The problem that x<=D is always true could be solved by using a conditional break
at the end of the loop.
if (x==D) break;
Has someone found a simpler solution?
Fred.Zwarts.