Re: [RFC] [PATCH] v4l2: use unsigned rather than enums in ioctl()structs

From: Nick Bowler
Date: Thu Apr 12 2012 - 13:22:51 EST


On 2012-04-11 23:32 +0300, Rémi Denis-Courmont wrote:
> From the perspective of the compiler, this is a feature not a bug. In
> C and C++, loading or storing a value in an enumerated variable
> whereby the value is not a member of the enumeration is undefined.

I'm afraid that this is not the case in C, although it may be in C++
(enums are very different in C++ than they are in C). In C, enum types
are required to be compatible with some integer type capable of storing
the values of all the enum members (see C11§6.7.2.2#4). Compatibility
is a very strong condition, and implies that the two types are
interchangable without affecting the meaning of the program (see
C11§6.2.7). Integer types have a number of specific requirements, one
thing that's relevant here is that they do not have "holes" in their
representable values: there is a minimum and maximum representable
value, and all integers between them are representable (C11§6.2.6.2#1).

Thus, while the choice of integer type used may depend on the values of
the corresponding enum constants, storing any value (regardless of
whether or not its a member of the enumeration) is subject to the same
rules as the implementation-defined compatbile integer type. This is
always well-defined for values within the range of the type.
(C11§6.3.1.3#1 and C11§6.3.1.4#1).

> In other words, the compiler can assume that this does not happen, and
> optimize it away.

No, a conforming C compiler cannot assume such assignments do not
happen, for the reasons outlined above.

Cheers,
--
Nick Bowler, Elliptic Technologies (http://www.elliptictech.com/)

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/