Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!att!ulysses!andante!alice!bs From: bs@alice.UUCP (Bjarne Stroustrup) Newsgroups: comp.lang.c++ Subject: Re: assigning int to enum Summary: enumerations are now types Message-ID: <9550@alice.UUCP> Date: 30 Jun 89 01:23:51 GMT References: <387@odi.ODI.COM> Organization: AT&T Bell Laboratories, Murray Hill NJ Lines: 70 root@odi.com (Operator) from Object Design Inc., Burlington, MA writes: > In ANSI C, it is ( I thought) legitimate to do the following: > > enum x { a, b, c} y; > int i; > > y = 1; > i = y; It is. > In the 2.0 release version of c++, a warning is emitted > for assigments of int typed to enums. > > In theory, benign warnings are supposed to be suppressed > unless one compiles with the +w option. > > Howcome this isn't suppressed? In C++, the example is not legal. There is no standard conversion from int to enums so the example is an error: enum x { a, b, c} y; int i; f() { y = 1; // error: int assigned to enum x, no standard conversion i = y; // ok standard conversion of enum to int } However, for compatibility only a warning is issued by 2.0: "", line 7: warning: int assigned to enum x The reason to disallow implicit conversions from int to enumerations in C++ (despite SOME cases being safe and SOME cases being legal ANSI C) is that only a few cases can be verified to be safe at compile time. For example: y = 1; // safe b==1 y = b; // better y = 4; // safe? It is legal ANSI C (I'm pretty sure) y = 1000; // safe? It is not guaranteed by ANSI C (I'm pretty sure) y = 1000000; // safe? not on your average computer. y = i; // safe? depends on the value of i. Rather than trying to cope with the insecurities by run-time checking (which would be most un-C-like) or simply allow whole classes of preventable errors (which would be most un-C++-like) we decided to base to rule on type alone (and not on the values). If you really want those assignments you can suppress any unwanted compiler interference: y = x(1); y = b; // better y = x(4); y = x(1000); y = x(1000000); y = x(i); Gradually introducing this rule by first using a warning and later turning it into an error seems prudent. If you find that too feeble, you might use the +p (`p' for `pure') option and get: "", line 7: error: int assigned to enum x The change of enumerations from mere typedefs for ints to types was done to bring C++ closer in line with modern C compilers and ANSI C.