Question about transfers in C ++

I tried using the 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 true because ++ f cannot be a valid enum enum - not in this case, but in the 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 that raises the question. What happens if I get a statement?

 foo f = foo(k); //k is not a valid foo value 

Is this behavior undefined?

EDIT: k is an int and has no 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 the help!

+4
source share
3 answers

I had a compilation error. I understand that this is not true, because ++ f cannot be a valid enumeration of foo.

No. This is an incorrect interpretation of the error. It does not compile, because operator++ does not exist for foo .

If you define operator++ as:

 foo & operator++(foo & f) { return f = foo(f+1); } 

Then ++f will compile and work: http://ideone.com/1GG09

As for foo(f+1) (or foo(k) ), this is normal. Internally, foo is an integral type. And this value can be anything that can be represented by a basic integral type.

Β§7.2 / 6 states:

For an enumeration, where e min is the smallest enumerator and e max is the largest, the enumeration values ​​are the values ​​of the base type in the range b min to b max , where b min and b max , respectively, are the smallest and largest values ​​of the smallest bit field that can store e min and e max ) . You can define an enumeration that has values ​​not defined by any of its counters.


EDIT:

  foo f = foo(100); //what value will have f after this according to the standard 

I think that the behavior is not specified here, as stated in the Standard in Β§7.2 / 9,

An expression such as arithmetic or enumeration can be explicitly converted to an enumeration type. The value does not change if it is in the range of values ​​of an enumeration of an enumeration type; otherwise, the resulting enumeration value is not specified.

For the listing range, see the previous quote.

+7
source

Defined behavior. A value that ends with f is not specified if k is outside the range of foo and matches k if it is within the range of foo .

The range of foo is 0 .. 2^(ld(n+2)+1) - 1 . That is, the values ​​of the bit field that can store all the values ​​of your enum (enum) constants.

+4
source

In this case, f will have the value k, but this does not match the label in enum . Think of enum as an unsigned int as a data type (unless otherwise specified) and identifiers inside enum constants.

0
source

All Articles