Hacker News new | ask | show | jobs
by SideQuark 587 days ago
You wrote

> But if they ARE the same size, the compiler doesn't similarly complain "your result may overflow the destination variable"

Adding two N bit unsigned integers together can require N+1 bits for the answer. So the compiler, if you add two intN and store into an intN, will warn you that "your result may overflow the destination variable". This is trivial since the compiler knows the types of all the variables in most all programming languages.

Plenty of compilers also use theorem proving to ensure some things do not overflow, so they can optimize accordingly. Thus, in the follow type of program

    int arr[10];
    for (int i = 0; i < 10; ++i)
       arr[i] = i;
The compiler, in languages where arrays are bounds checked, can deduce with certainly that arr is not out-of-bounds here, and can remove costly bounds checking.

But if you have

      int arr[10];
      func setLen(int len)
          for (int i = 0; i < len; ++i)
              arr[i] = i;
Would need bounds checking given only this snippet. But there's more. If the program can prove that setLen is never called (or callable) with len > 10, then once again it can remove the bounds checking.

Modern compilers do an every increasing amount of amazing things to make all this work transparently.