Reputation: 303
What does it mean to define an array with enum variable as array size?
For example I have the following code:
typedef enum
{
D_ROM_RDE_GROUP_0 = 0x0,
D_ROM_RDE_GROUP_1,
D_ROM_RDE_MAX_GROUPS
}E_ROM_RDE_GROUPS;
U_08 pPlaneCopy[D_ROM_RDE_MAX_GROUPS];
I don't understand it...
Thanks for the help.
Upvotes: 8
Views: 14249
Reputation: 23218
This is a techique often used to define an array that is in some way related to the values in an enum. For a simple example:
enum {
ZERO,
ONE,
TWO,
THREE,
MAX_VALUE //has value of 4
};
because the natural value of an enumerated element starts at zero, and increments by one for each member, the final value will always be useful to initialize an array, of any type (strings
, ints
, floats
, etc) for a number of elements equal to that final value. eg.
int numbers[MAX_VALUE];//an array with 4 elements
int i;
You can then use MAX_VALUE to guarantee treating the array in a loop without going beyond the bounds of the array, eg. something like:
for(i=0;i<MAX_VALUE;i++)//will loop 4 times
{
numbers[i]=i;//assigned a value equal to its namesake, for i < MAX_VALUE
}
Given this explanation, the enum in your original post is simply being initialized with a value of 2:
U_08 pPlaneCopy[D_ROM_RDE_MAX_GROUPS];
is the same as
U_08 pPlaneCopy[2];
Upvotes: 2
Reputation: 23058
An unsigned integer is automatically assigned to each enum elements if not explicitly specified otherwise. Thus, with your enum declaration, D_ROM_RDE_GROUP_0
equals to 0
, D_ROM_RDE_GROUP_1
equals to 1
, and D_ROM_RDE_MAX_GROUPS
equals to 2.
Thus, the declaration
U_08 pPlaneCopy[D_ROM_RDE_MAX_GROUPS];
is equivalent to
U_08 pPlaneCopy[2];
Which means, you declared an array with one U_08
element corresponding to each possible value in E_ROM_RDE_GROUPS
assuming D_ROM_RDE_MAX_GROUPS
is not a value used otherwise.
Upvotes: 1
Reputation: 409196
The first thing to remember is that enumeration values are compile-time constant. The other thing is that enumeration values (unless initialized to a specific value) increases. So in your case D_ROM_RDE_GROUP_0
is equal to 0
, D_ROM_RDE_GROUP_1
is equal to 1
and D_ROM_RDE_MAX_GROUPS
is equal to 2
.
This means that when you declare the array, it's basically the same thing as
U_08 pPlaneCopy[2];
Upvotes: 9
Reputation: 10162
The enum value D_ROM_RDE_MAX_GROUPS is actually an integer value, in your case: 2. So you are defining an array with two elements. Probably the two elements will be accessed by the indices : D_ROM_RDE_GROUP_0 and D_ROM_RDE_GROUP_1
Upvotes: 1