federico-busato / Modern-CPP-Programming

Modern C++ Programming Course (C++03/11/14/17/20/23/26)
https://federico-busato.github.io/Modern-CPP-Programming/
11.91k stars 798 forks source link

Proposed rewording for "3. Basic Concepts II", example on page 21 #80

Closed binary-manu closed 6 months ago

binary-manu commented 6 months ago

The provided example says:

image

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:

image

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,:

image

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.

federico-busato commented 6 months ago

thanks for the detailed explanation, @binary-manu. I did some experiments with compiler-explorer and I reorganized the slide as follow image