I am very new to C++ and am wondering what the difference between the two bits of code below is,in terms of what it's really doing and if I should be using one, rather than the other. They both compile fine with no error messages, and have seen examples of both of these used in different circumstances.

enum Days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
Days DayOff;
int x;
cin >> x;
DayOff = (Days) x;
enum Days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
Days DayOff;
int x;
cin >> x;
DayOff = Days (x);

Recommended Answers

All 3 Replies

Member Avatar for GreenDay2001

This is typecasting, i.e. changing a data from one type to another. Both are same and works same. Enumerators are nothing but named integer constants. If there are n elements in that enumerators then each one will be alloted a unique integer from 0 to n-1, until you specify something else. So Sunday will be 0 and Wednesday will be 3. So, here you take an integer and typecast it into Days.

here it is not effecting where you put the brackets...but take care of brackets when you want to typecast the result of an expression....

example... Dayoff= (Days)((x+y-5)*z);

>DayOff = (Days) x;
This is a C-style type cast. It's taking the value of x and attempting to coerce it into the Days type. You should avoid casting whenever possible, because types aren't always interchangeable, and especially in this case you can get in over your head very quickly.

>DayOff = Days (x);
This is a C++-style type cast. It does the same thing as the C-style type cast, except it uses a constructor call syntax.

Another form of C++ casting is static_cast<Days>(x) .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.