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);

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) .

This article has been dead for over six months. Start a new discussion instead.