In a system I am maintaining, users request elements from a collection from a 1-based indexing scheme. Values are stored in 0-based arrays in C++ / C.
Is the following hypothetical code portable if 0 is erroneously entered as the input to this function? Is there a better way to validate the user’s input when converting 1-based numbering schemes to 0-based?
const unsigned int arraySize;
SomeType array[arraySize];
SomeType GetFromArray( unsigned int oneBasedIndex )
{
unsigned int zeroBasedIndex = oneBasedIndex - 1;
//Intent is to check for a valid index.
if( zeroBasedIndex < arraySize )
{
return array[zeroBasedIndex];
}
//else... handle the error
}
My assumption is that (unsigned int)( 0 - 1 ) is always greater than arraySize; is this true?
The alternative, as some have suggested in their answers below, is to check oneBasedIndex and ensure that it is greater than 0:
const unsigned int arraySize;
SomeType array[arraySize];
SomeType GetFromArray( unsigned int oneBasedIndex )
{
if( oneBasedIndex > 0 && oneBasedIndex <= arraySize )
{
return array[oneBasedIndex - 1];
}
//else... handle the error
}
For unsigned types,
0-1is the maximum value for that type, so it’s always>= arraySize. In other words, yes that is absolutely safe.