devxlogo

Assigning Integers to enum Variables

Assigning Integers to enum Variables

C and C++ differ in their handling of enum types. While C allows you to assign a plain int to an enum variable, C++ doesn’t. Therefore, a C compiler will accept the following code while a standard compliant C++ compiler won’t:

 enum Direction (West, North East, South};Direction d;d = 1; /* OK in C, d equals 'North' */

C++ has stricter type safety rules. A standard-compliant C++ compiler will reject the assignment of 1 to d. You have to use an explicit cast for this to work, or better still, always assign an enumerator to an enum variable:

 d = static_cast  (1);  // fined = East;

devx-admin

Share the Post: