1
u/Kenkron 10d ago
Rust users: Allow us to introduce ourselves
2
u/luciferoussky72 10d ago
*unsafe block standing right behind you*
1
u/Kenkron 10d ago
Dude, it was totally necessary to makey own double -linked list, which I need to make my blazingly fast leftpad replacement library! And I'm sure I made no mistakes, because I told Claude "make no mistakes".
1
u/luciferoussky72 10d ago
Whenever I see 500 lines of Rust I think that it could be 50 lines of functionally identical C++ lol
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
4
u/HyperWinX C++ 17d ago
They dont "see" undefined behavior though. Because... it is undefined.