I tried to use an enum in a for loop like this:
enum foo
{
foo_0,
foo_1,
foo_2,
foo_3,
...
foo_n,
foo_count
};
for(foo f = foo_0; f < foo_count; ++f)
and I had a compilation error. I understand that this is not valid because ++f might not be a valid foo enum – not in this case but in general case so I switched the for loop to this:
for(foo f = foo_0; f < foo_count; f = foo(f+1))
which compiles fine. But this rises the fallowing question. What happens if I have the fallowing statement?
foo f = foo(k); //k is not a valid foo value
Is this undefined behavior?
EDIT: k is an int and it hasn’t any corresponding value in foo
EDIT2:
enum foo
{
foo_0,
foo_1,
foo_2,
foo_3
};
foo f = foo(100); //what value will have f after this according to the standard
Thanks for help!
No. That is wrong interpretation of the error. It doesn’t compile because there is no
operator++defined forfootype.If you define
operator++as:Then
++fwould compile and work : http://ideone.com/1GG09And as for
foo(f+1)(orfoo(k)), then that is okay. Internally,foois an integral type. And it’s value can be anything which can be represented by the underlying integral type.§7.2/6 says,
EDIT:
I think the behavior is unspecified here, as the Standard says in §7.2/9,
For enumeration range, see the previous quotation.