c++ - Declearing enum and setting values manually not in increasing order -


is definition of enums in c++ , setting values in random order valid? used in well-known code? e.g.:

enum esampletype{ stpositivecontrol='p', stnegativecontrol='n', stsample='s' }; 

vs2008 compiles without warnings. wonder whether gcc would. in opinion, least harms "least surprise rule" iterating on values using

for(int i=stpositivecontrol; i<=stsample; ++i) 

would fail.

p.s: rationale approach: in db application i'm defining wrapper methods. columns contain "constants" encoded single char. i'm trying make little more type safe.

yes valid.

there example use of in book the c++ programming language (3rd edition) bjarne stroustrup, section "6.1 desk calculator [expr.calculator]" (and more precisely "6.1.1 parser [expr.parser]"), parser code of simple arithmetic calculator. here's excerpt:

the parser uses function get_token() input. value of recent call of get_token() can found in global variable curr_tok. type of curr_tok enumeration token_value:

enum token_value {     name,       number,     end,     plus='+',   minus='-',  mul='*',    div='/',     print=';',  assign='=', lp='(',     rp=')' }; token_value curr_tok = print; 

representing each token integer value of character convenient , efficient , can people using debuggers. works long no character used input has value used enumerator – , no character set know of has printing character single-digit integer value. (...)

(that last sentence specific example, because enumeration mixes "default-value" , "explicit-value" enumerators , wants each 1 unique.)

however it's educative example (and notably uses global variable, , caps names enumerators when should reserve them macros (but stroustrup doesn't macros :p)).

now, indeed can't iterate on (at least plain for loop; see this question). (and as james kanze pointed, enum's values not ordered, contiguous, , unique.)


Comments