As others have pointed out, you are allowed to point one past. But do remember that it is NOT allowed to point one element before the first. So you might want to be careful if you write algorithms that traverses arrays backwards. Because this snippet is invalid:
void foo(int *arr, int *end) {
while(end-- != arr) { // Ouch, bad idea...
// Code
}
// Here, end has the value arr[-1]
}
That's because, when end
points at the same element as arr
, the condition will be false, but after that, end
is decremented once more and will point to one element before the array, thus invoking undefined behavior.
Do note that apart from that, the code works fine. To fix the bug, you can do this instead:
void foo(int *arr, int *end) {
while(end != arr) {
end--; // Move end-- to inside the loop, in the very beginning
// Code
}
// And here, end is equal to arr, which is perfectly fine
}
The code in the loop will work exactly as before. The only difference is that end
will not be decremented the last time.