On the system that I support, users request items from the 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 was mistakenly entered as an input to this function? Is there a better way to check user input when converting numbering schemes based on 1 to 0?
const unsigned int arraySize; SomeType array[arraySize]; SomeType GetFromArray( unsigned int oneBasedIndex ) { unsigned int zeroBasedIndex = oneBasedIndex - 1;
My assumption is that (unsigned int)( 0 - 1 ) always larger than arraySize ; it's true?
An alternative, as some of them suggested in their answers below, is to check oneBasedIndex and make sure 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]; }
source share