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 < Direction > (1);  // fined = East;
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: