Re: Question about "enums"



Ian Collins <ian-news@xxxxxxxxxxx> writes:

John Devereux wrote:

Ian Collins <ian-news@xxxxxxxxxxx> writes:

Nothing wrong with that, I was referring to code that assigned invalid
values to an enum.

But how is the the compiler supposed to *know* they were invalid? In
the code you snipped, I only mentioned the "special" values in the
enum, yet in fact any integer could be "valid".

Sorry if I got carried away with the snippers...

The compiler would know because it knows the legal set of values for the
enumeration. For this to work, math operations on enums will have to be
removed. In my opinion, they don't make sense, given a set of integers
{ 1, 5, 7, 9 } what does incrementing a member of the set do?

Restoring your code:

enum
{
START=000,
REJECT,
QUEUE,
BRAKE,
/*...*/
ALARM=020,
TEST,
NSIGNALS=040
};

turn_on(REJECT);
turn_off(TEST);

/* hardware test */
for(i=0; i<NSIGNALS; i++)
{
turn_on(i);
delay();
turn_off(i);
}

I had assumed that i was an int (you didn't show the declaration).

Sorry, yes, i was an int. But turn_off() could be declared a taking an
enum argument. But actually I suppose it could just as well be
declared taking an int, and in fact that is what I do in practice.

I thought your suggestion was that compilers should reject assignments
of values that are not in the enum declaration.

Indeed it is.

So it would be OK to convert an enum to an arbitrary int, but not an
int to an enum type?

--

John Devereux
.



Relevant Pages

  • Re: Using a Class as parameter
    ... should I create a new file for the enum then? ... > int levelWidth; ... > declaration of CLevel is read. ...
    (microsoft.public.vc.language)
  • Re: New C features proposal
    ... int sum; ... prototype thus the following would be illegal: ... void f1; ... void message(const char *msg, enum level level=LVL_WARN, ...
    (comp.std.c)
  • [git patches] net driver updates for .27
    ... static int lance_open (struct net_device *dev) ... enum mac8390_type type); ... unsigned int fifo_count, timeout, reg; ...
    (Linux-Kernel)
  • Re: __attribute__ ((mode(__byte__)))
    ... int is_A (enum my_enum my_val) ... they're actually of type int. ... An "enum" declaration can be used to declare a series of constants ... without declaring a named type. ...
    (comp.lang.c)
  • Re: why still use C?
    ... I was talking about the malloc expression, ... >>the assignment expression. ... >>enum parameter is not an error in C, but in my coding style it's a mistake). ... I took it you meant "int where an enum" is expected, ...
    (comp.lang.c)