Hi,
Note: I do know the properties of enumeration, but I have a question nonetheless...
If you define an enumeration, like this:
enum {aaa, bbb, ccc};
, then 'aaa' represents a value of 0, 'bbb' a value of 1 and 'ccc' a value of 2. All clear.
And even an enumeration like this:
enum {aaa, bbb, ccc=8, ddd};
, then 'aaa' represents a value of 0, 'bbb' a value of 1, 'ccc' a value of 8, and 'ddd' a value of 9. Also clear.
But why do I often encounter enumerations which members are ALL initialised? Like:
enum {aaa=0, bbb=1, ccc=2, ddd=3};
. What is the underlaying thought, that I may have eluded here? To me it looks like the enumeration is simply degradated to a series of '#define'.
This question arose after going through 'gfx.h' where I encountered 'enum enPixelFormat': a perfect example of this 'degradation'.
OldFart
An enumeration is an actual C/C++ type, while a #define is just a text substitution.
So if, for example, you declare a variable or struct field as holding a particular enumeration, the compiler will warn you if you try to store anything else there, or try to assign that value to a variable or function parameter of some other type. You don't get that with #define'd constants.
As in gfx.h, a typedef is often created to "wrap" the enum, so you don't need to keep typing 'enum' every time you declare something using it.
@msteed
Thanks for your reply, but as I already mentioned in my first post:
/* Edit: */
This might probably be true for c++. As far as I can tell, there is no such warning in C.
The gist of my question is why would anyone explicitly initialise EVERY value in an enumeration, thereby negating the whole concept of the enumeration process.
OldFart
I can only speculate, as I don't do this in my own code. One possible reason is as a safety measure- if the order of the values in the enumeration gets changed or something gets added or removed, the correspondence between names and values won't change. This is especially of benefit in a public header like gfx.h, where lots of other code may depend on the enumeration values.
Another possibility is as a debugging aid- it's easier to look up what name goes with a value when you don't have to count from the first name up to the one corresponding to the value every time.
@OldFart
It does seem redundant when looking at manually set enum lists. It would also seem error prone if one value was missed as it would fill it in automatically. But one thing does stand out. It does look like one way to associate a namespace to a list of values. I don't know if that can be used to track them futher down the line. But it can be used to group values under a common name and give enum lists a name.