User-defined enumerated types behave differently in C++ than their C counterparts. For example, C enum types are compatible with the type int. This means they can be cross-assigned with no complaints from the compiler. However, in C++ the two types are incompatible.
Another difference between C and C++ enumerated types involves the syntax shorthand when you define C++ enumvariables. The following example program highlights the enumerated type differences between the two languages:
// // enum.cpp // C++ program demonstrates how to use enumerated types and // how C++ enumerated types differ from C enumerated types // Copyright (c) Chris H. Pappas and William H. Murray, 1998 //
#include <iostream.h>
typedef enum boolean { FALSE, TRUE };
void main(void) { // enum boolean bflag = 0; legal C, but illegal C++ statement boolean bcontinue, bflag = FALSE;
bcontinue = (boolean)1;
bflag = bcontinue; }
This code starts by defining the enumerated type boolean, which is a standard type in several other high-level languages. Because of the ordering of the definition —FALSE, then TRUE—the compiler assigns a zero to FALSE and a 1 to TRUE. This is perfect for their logical use in a program.
The statement, commented out in the main( ) program, represents a legal C statement. Remember, when you define enumerated variables in C, such as bflag, you must use the enum keyword with the enumerated type’s tag field—in this case, boolean. Since C enum types are compatible with int types, it is also legal to initialize a variable with an integer value. This statement would not get past the C++ compiler. The second statement in main( ) shows the legal C++ counterpart.
The final two statements in the program show how to use enumerated types. Notice that in C++, an explicit cast (boolean), is needed to convert the 1 to a boolean-compatible type.
User-defined types cannot be directly input from or output to a file, as you may recall. Either they must go through a conversion routine or you can custom overload the >> and << operators, as discussed in Chapter 12.