Reputation: 7623
So as I understand when initialising an "empty" array in C (as shown below), you are initialising each element to 0 (since C does not have a null value).
int values[5] = {0}; // each element has a value of 0
However, if I assign a few random values to my int array as shown below...
// examples for assigned values, but they can be from all over the range
values[0] = 1;
values[1] = 0;
values[2] = -1;
How would I check which elements in my array have yet to have a value assigned to it?
I.e. what is the best way to approach the following?
for (int i = 0; i < 5; i++) {
// find out whether this element was already assigned a specific value
if (array[i] == ??? )
{
// the element has yet to be assigned
}
}
Upvotes: 0
Views: 1197
Reputation: 26703
Here is an approach for the more difficult situation that the possible values assigned explicitly to the array elements cover all of the range of the used data type (otherwise see other answer, i.e. init the whole array to an unused value):
You should make another array of the same size, initialise it completely with values which indicate "not yet initialised".
Then, whenever you initialise an array element of the original array, write a value which indicates "already initialised" to the second array, at the same index.
That way the question "has this entry been initialised?" can be answered by looking at the same index in the second array.
However, initialising an array can be done with
int values[5] = {0};
Thils will initialise the first entry with the given "0" and all the rest implicitly with "0" as default value (which is not related to the given zero).
Then the answer to "initialised?" is always "yes".
(I see you already picked up the correct array initialisation from comments. I keep this answer part for clarity about the meaning of the single value used.)
Upvotes: 3
Reputation: 35154
For scalar data types as int
, C indeed does not have a commonly accepted / defined value for "undefined"; it's rather subject to the individual code if one interprets a specific value in the range of int
as "undefined".
Usually you will define such a value with something that is out of the "practical" range for your use-case; For example, if the values denote an index of an array, one could write #define UNDEF_INDEX UINT_MAX
, because it is unlikely that an array will get such a size. For int, you could say #define UNDEFINED_VALUE INT_MIN
.
#define UNDEFINED_VALUE INT_MIN
for (int i = 0; i < 5; i++) {
array[i] = UNDEFINED_VALUE;
}
...
for (int i = 0; i < 5; i++) {
if (array[i] == UNDEFINED_VALUE )
{
// the element has yet to be assigned
}
}
Upvotes: 2