I have
enum Colour { white, pink, yellow, blue } Colour;
and I would like to do something like this:
for (int colour in Colour){ // Do something here. }
Can I do this and if yes, how? Thanks for your help!
you can iterate the elements like: for(int i=Bar; i<=Last; i++) { ... } Note that this exposes the really-just-an-int nature of a C enum. In particular, you can see that a C enum doesn't really provide type safety, as you can use an int in place of an enum value and vice versa.
Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.
The C standard specifies that enums are integers, but it does not specify the size. Once again, that is up to the people who write the compiler. On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less.
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.
Although the question is already answered, here are my two cents:
enum Colour { white = 0, pink, yellow, blue, colorsCount // since we count from 0, this number will be blue+1 and will be actual 'colors count' } Colour; for (int i = 0; i < colorsCount; ++i) someFunc((Colour)i);
I guess it's not that bad and is pretty close to the fast enumeration you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With