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 < Direction > (1);  // fined = East;
See also  Does It Make Sense to Splurge on a Laptop?
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist