Hacker News new | ask | show | jobs
by kccqzy 729 days ago
> things that people reasonably can assume would work but are UB anyway (signed integer overflow.)

Since when is it reasonable to assume that?

> Then you have weird edge cases like assigning the return value of a two argument std::max involving temporaries to a reference

You have a reference to a temporary. Reference lifetime extension is a thing. No UB there. Completely defined and supported.

1 comments

When all hardware built for decades uses two's complement arithmetic and even the standards bodies have noticed this (e.g. https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2218.htm) it's not remotely necessary to assume that overflowing a signed integer is undefined behaviour. It's totally defined exactly what that instruction is going to do on any hardware any electrical engineer is willing to build.

However, some benchmarks use iteration on a signed integer, and assuming that loop terminates makes it slightly faster, so in order to retain that marginal advantage over other languages, signed iteration shall be assumed to never overflow.

This is very typical of the C++ experience.

That's not why it's ub. It's ub to allow compilers to optimize x*2/2 to just x. If you want overflow, you can use unsigned, which has been defined to follow 2's complement semantics for quite some time.