1). Your code prints the value of the enum, not the index. In your specific example, the index is the same as the value (by default, the first value of an enum gets the numerical value 0, and the rest get consecutive increasing values.
To check:
int main()
{
enum day{sunday = 5,monday,tuesday,wednesday,thursday,friday,saturday};
day d=wednesday;
cout<<d; // will print 8 (as in 5 + 1 + 1 + 1)
return 0;
}
If by "print the value" you meant printing "wednesday", you should do this:
enum day{sunday,monday,tuesday,wednesday,thursday,friday,saturday};
std::ostream& operator << (std::ostream& out, const day d)
{
static const char *as_strings[] = {"sunday", "monday",
"tuesday", "wednesday", "thursday", "friday", "saturday"
};
return out << as_strings[static_cast<int>(d)]; // this only works
// for enum values starting from 0 and being consecutive
// otherwise you should use a switch(d) and
// print each value separately
}
int main()
{
day d=wednesday;
cout<<d; // will print wednesday
return 0;
}
Edit:
2) In what situation will I prefer anonymous enum over enum
You prefer an anonymous enum when you do not need to pass it as a parameter, but need to assign meaningful names to constant numeric values:
my_object record_to_myobject(record& r)
{
enum {id, value1, value2}; // indexes within record
int result_id = r[id]; // much more meaningful than r[0]
int result_value1 = r[value1];
int result_value2 = r[value2];
return my_object{result_id, result_value1, result_value2};
}
It's fine to use an anonymous enum here because where you pass the value as argument, you need an int, not an enum type. If you need an enum type, then you have to give it a name. Otherwise, you do not.