Michael Press said:
I want to index into a list using offset one indexing.
The obvious thing to do is make a pointer that points
one element before the list.
void work_on_stuff(int *offset0, int length)
{
int offset1 = offset0 - 1;
for(idx = 1; idx <= length; idx++)
{
... offset1[idx] ...
}
}
Is this likely to fail? Possible to fail?
Very unlikely to fail? Not guaranteed by the standard?
(Assuming 'offset0' actually points to the start of an array
rather than somewhere further on
Not guaranteed by the Standard, and a bad idea even though
currently it probably works in many (most?) compilers.
As compilers get more aggressive at code improvement, code
like this with undefined behavior gets more likely to cross
over into the compiler equivalent of the Neutral Zone. If
and when that happens, most likely one of two things will
result: one, the optimizer won't realize its assumptions
have been violated, and bogus code will be generated; or
two, the optimizer _will_ realize its assumptions have been
violated, but will fall back to an ultra-conservative
position for code generation, preserving correctness but
sacrificing performance.
Neither of these possibilities is really good, but what's
worse is that they might start happening any time there is a
switch to a new compiler (or a different choice of compiler
options); worse still, unless you are very careful you will
start to get bad results before realizing what has happened.
There's an old Polish proverb that says, Even if you are the
person who buried all the land mines, walking through a
minefield is no fun.
(TIA: "an old Polish proverb" isn't really a Polish
proverb - it's meant to be humorous for the cognoscenti.)