r/programmingmemes 17d ago

compilers be like

Post image
140 Upvotes

20 comments sorted by

View all comments

1

u/RedAndBlack1832 17d ago

They actually just assume it won't happen which leads to... interesting behaviour. You can set up situations in which you get calls that were never made this way but the most obvious example is just integer overflow lol. If you assume overflow never happens that can cause weird optimizations that won't work very well if you do actually get overflow

2

u/luciferoussky72 16d ago

Well, yeah. Although do keep in mind that it’s only signed overflow that’s UB. It’s UB specifically because it lets the compiler assume that x + n is always greater than x when x is signed. Unsigned overflow is defined and it just wraps back to 0

1

u/scalareye 16d ago

What do different compilers do if signed overflow or underflow happens. Can you tell the compiler to act in a specific way for different undefined behaviors. I know you can enforce strict checking so it won't do some of the extra optimizations

It's also fine with floating point numbers but your code won't like the result either.

If you were making an integral calculator for example, you should accept input as a string and reject invalid strings.

Floating points have signed infinity for their maximum value and all of your computations will end up collapsing to infinity. Can also get NaN for 0 / 0 and that also ruins your computation without telling you when it happened. You can tell the compiler to error out if it happens though.

2

u/luciferoussky72 16d ago

So, the reason it was initially undefined behaviour is because for a long time the C and C++ standard didn’t specify *how* to store numbers. Things like endianness being inconsistent meant you couldn’t make signed overflow defined behavior without standardizing a bunch of other things.

Ironically, C++17 actually did standardize how to store numbers, but signed overflow remained undefined behavior for optimization reasons. For example, having it undefined means the compiler can assume that x + n is greater than x and optimize around that.

2

u/RedAndBlack1832 16d ago

The last paragraph is what i meant to be getting at :)