Reputation: 1168
I have some macros defined such as
#define NUM_A 3
#define A1 10
#define A2 100
#define A3 8
The total count and the values are specific to the device. Now I need an array looks like
int Array[NUM_A]={A1, A2, A3};
Now, if the total number, NUM_A changes to 4, and I have defined the macro A4, but I forget to append A4 to the array. The actual Array would be {A1, A2, A3, 0}. There won't be error when compiling. The error is also hard to be found when running the program. It's more likely to be happen when I write the macros in the header file and declare the array in a source file. Can I write a looped macro to generate the array by the defined macros NUM_A, A1, A2 and A3? Or can I write an assert or something else to warn myself if the error occurs when compiling or running?
Upvotes: 0
Views: 128
Reputation: 23218
In addition to declaring your variable with open array operators as A.M.D. has shown:
int arr[] = {A1, A2, A3};
You can also define a shorter representation of sizeof arr/sizeof arr[0]
, by defining a macro to replace that statement anywhere in your code where arr
is defined like this:
#define ARR_SIZE sizeof arr/sizeof arr[0]
The macro will evaluate to the number of array elements at run-time, And accommodates changes to number of elements in the array between run-times, with no need to edit the macro.
For arr[] = {1,2,5,8,9,3};
ARR_SIZE will evaluate to 6
For arr[] = {1,2,5,8,9,3,4,7,1,0,4};
ARR_SIZE will evaluate to 11
This is a useful code readability technique for things such as loops:
for(i=0;i< ARR_SIZE;i++); // is more readable
for(i=0;i< sizeof arr/sizeof arr[0];i++); // is less readable
Upvotes: 0
Reputation: 5298
Just a question/suggestion.
Do you really need "NUM_A" ? Atleast from the code snippet point of view, it is not required. Not sure if you are using it elsewhere for some other purpose.
You can declare the array as:
int Array[] = {A1, A2, A3}; /* So this becomes the only place to be modified, just add A4 in the future. No confusion with array size */
NUM_A is equivalent to "sizeof Array / sizeof Array[0]".
Example:
int arr[] = {A1, A2, A3};
int i;
for(i = 0; i < sizeof arr / sizeof arr[0]; i++)
{
printf("%d\n", arr[i]);
}
Upvotes: 1
Reputation: 60681
You can assert that the array is of the expected size:
assert(sizeof(Array) == NUMA * sizeof(Array[0]));
That's a runtime check. There are various ways of doing it at compile-time depending on your compiler version; see Static assert in C
Upvotes: 0