4 ms·
It probably is easier to reserve an array item for that sentinel marker. In either case, it requires your array to be writable, and you’re giving up having mul
by Someone 8y ago
It probably is easier to reserve an array item for that sentinel marker.
In either case, it requires your array to be writable, and you’re giving up having multiple searches through the same array operating at the same time.
Also, on modern hardware, the ‘ran out of items’ check is essentially free.
Nowadays, the only realistic use for this would be a case where you have a fixed-size array that you search frequently, where the same end marker can be used all the time, so that you can add that sentinel marker once.
I’ve a hard time thinking of examples, but do not rule out cases inside OS kernels or search trees for computer chess or similar games.
A variant would be to use this in C, and, when the program allocates N+1 chars to hold a string of length <N, allocate N+2 chars, and set the last one to zero, to ‘guarantee’ that later strlen or strcpy calls don’t run on forever, even if a strncpy copies N+1 bytes. I don’t see how that ‘guarantee’ would add much, though.
- Arnavion 8y ago>Nowadays, the only realistic use for this would be a case where you have a fixed-size array that you search frequently, where the same end marker can be used all the time, so that you can add that sentinel marker once. The sentinel needs to be identical to the value you're searching for, otherwise you're trading "compare a pointer" for "compare a value with an arbitrary equality implementation" which is no better (and probably worse).