This is more of an etiquette question than anything else, but when creating new arrays what value, other than zero, should I use to indicate an empty space in the array? For example:
int* arr;
arr = new int[10];
When I create a new array like in the code above, the array will be filled with ten zeroes. The issue I'm having is that I want to use underscores when printing the array to indicate empty spaces, however, I also have zeroes as part of my data set in the array. So, should I just fill the empty array with some arbitrary value that is unlikely to show up in my data set (like -32000 for example), and use that as the indicator for empty space, or is there some sort of null value that I could use instead, so that I can know for a fact that the value at that specific index is definitely an empty space?
CodePudding user response:
should I just fill the empty array with some arbitrary value that is unlikely to show up in my data set
Well, unlikely is not the same as a value that you know for certain will not appear in the data. Generally speaking you do have some idea of the range of values and it is indeed easier to use a sentinel value outside that range to indicate nullity.
However, in cases where there is no such value, the canonical way to handle this situatuion in modern C is to use std::optional<int>
. The standard library's optional
is a way of turning any type into a nullable type.
CodePudding user response:
Please note that questions of "taste" are generally frowned upon in stack overflow.
With that said, here's my preference:
Something that cannot masquerade as a valid value, like NaN, makes a good placeholder. If that isn't an option, then as you said, a value that will not/is not allowed to appear in the data set works.