Mail Archives: djgpp/1996/04/23/10:38:09
Christoph P. Kukulies wrote:
> about style I would state that defining a pair of boolean variables
> as an enum is bad style anyway since I'm not sure where is guaranteed
> that the compiler always chooses the value 0 for the first
> entry in the enum list - maybe it's defined in ANSI somewhere.ANSI C stipulates that the first identifier in a enum shall have the
value 0 and every subsequent identifier will take the value one higher
than the identifier preceding it. Hence
enum bool { false, true };
is quite safe. I am not 100% certain that the C++ standard treats enums
in the same manner; the ARM also stipulates a zero start with unit
increments, although it is not quite as precise on what happens in the
presence of assignments; however, I see no reason why the final
standard should diverge from C. In any case, no matter what the standard
says the following will always work:
enum bool { false = 0, true = 0 };
The only problem associated with this definition of bool is when an
int or comparison is supplied where a bool is requested, eg.:
bool f() { /*...*/ return a == b; }
void g(bool b); /*...*/ int i = 0; g(i);
This problem can be worked around by typecasting:
bool f() { /*...*/ return bool(a == b); }
void g(bool b); /*...*/ int i = 0; g(bool(i));
The beauty of this approach is that the code will continue to work on
compilers that have bool built in.
I hope this trivia bombardment doesn't cause any boredom-related deaths!
- Raw text -