Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: All
Aug 4, 2000

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);  // fine
d = East;
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date