However, if the if were to be removed entirely, we would be able to call the function with any negative index and it would be used to access the array, without any checks.
What actually happens (at least with clang when compiling with -O3) is that the code is generated as follows:
The if statement is still there, in form of a jl opcode, but instead of checking if the parameter is negative after the increment, it checks if it's smaller than -1 before the increment. This makes sense, since the only way to get a negative number after an increment, if we ignore overflow, is to start with a number lower than -1. This code thus crashes if the passed index is INT_MAX.
As a side note, gcc generates it differently,:
and thus it will not crash in this example.
So I would propose to reword the comment not to mention the removal of the if statement, since it must remain to prevent real negative indices from being used.
The provided example says:
However, if the
if
were to be removed entirely, we would be able to call the function with any negative index and it would be used to access the array, without any checks.What actually happens (at least with
clang
when compiling with-O3
) is that the code is generated as follows:The
if
statement is still there, in form of ajl
opcode, but instead of checking if the parameter is negative after the increment, it checks if it's smaller than -1 before the increment. This makes sense, since the only way to get a negative number after an increment, if we ignore overflow, is to start with a number lower than -1. This code thus crashes if the passed index isINT_MAX
.As a side note,
gcc
generates it differently,:and thus it will not crash in this example.
So I would propose to reword the comment not to mention the removal of the
if
statement, since it must remain to prevent real negative indices from being used.