Re: enum safety
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Fri, 08 Feb 2008 12:54:12 -0800
Sard <Sardaukary@xxxxxxxxx> writes:
Page 39 K&R2 says
'Although variables of enum types may be declared, compilers need not
check that what you store in such a variable is a valid value for the
enumeration'
Right. In fact, the above statement is too weak; compilers aren't
even allowed to perform such checks (or at least they're not allowed
to reject the program if such a check fails).
gcc produces an error for the code below as I'm trying to assign a
pointer to char to the a variable of type colour. Is gcc going beyond
the call of duty? Why would the standard allow compilers to accept
such code?
#include <stdio.h>
#include <limits.h>
char* c=0;
enum colours {
Red,Blue
};
int main ()
{
enum colours purple =c ;
return 0;
}
The compiler needn't check for a valid value. It must check for a
valid type. In this case, c is of type char*, purple is of type enum
colours, and there's no implicit conversion. This really has nothing
to do with it being an enum type.
What K&R is talking about is something like this:
#include <stdio.h>
int main(void)
{
enum colors { red = 10, blue = 20 };
enum colors purple = 15;
printf("purple = %d\n", (int)purple);
return 0;
}
This is perfectly legal; a particularly picky compiler might warn
about it, but it must accept it and it must produce the output
purple = 15
An enum type declaration really does two things. It creates an
enumerated type (which must be compatible with some existing integer
type and must be able to hold all the specified values), and it
creates a series of constants (which, oddly enough, are of type int,
not of the enumerated type). It looks a lot like the enumerated types
you might see in other languages such as Pascal, and you can use it
for the same purposes if you're careful, but it's really quite
different.
Note that this provides a cute mechanism for creating a named constant
of type int:
enum { MAX=1000 };
The type is anonymous and is never used; MAX is a constant of type int
with the value 1000. This is arguably cleaner than a macro, but it
doesn't extend to types other than int.
--
Keith Thompson (The_Other_Keith) <kst-u@xxxxxxx>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.
- Follow-Ups:
- Re: enum safety
- From: Eric Sosman
- Re: enum safety
- References:
- enum safety
- From: Sard
- enum safety
- Prev by Date: Re: A solution for the allocation failures problem
- Next by Date: Re: The comma operator, and assigning twice between sequence points
- Previous by thread: Re: enum safety
- Next by thread: Re: enum safety
- Index(es):
Relevant Pages
|