by torstenvl · 4y ago · 0 comments
> I’d like to have . . . a 63 bit unsigned integer. . . . However, it is undefined behavior if it ever stores a negative value.
No. There is no "debug mode" for undefined behavior. Undefined behavior is always undefined behavior.
It also doesn't "automatically come[] with a precondition that it cannot be negative" - only that if it's ever negative, your program might crash for reasons that cannot be found in your code.
If you really want this, use uint64_t and treat any value over 0x7fffffffffffffff as an error.
Curious about the drive-by downvoters: Can you point out where you think I'm wrong?
This is not true; the standard explicitly allows implementations to, and I quote directly from the standard, "behave during translation or program execution in a documented manner characteristic of the environment".
This idea that undefined behavior is always undefined behavior and there's no way to reason about it is purely academic, incorrect, and not in any way justified either by source material or in practice.
As for debugging undefined behavior, UBSan [1] is an excellent tool that is well supported by GCC and clang, and MSVC is working to add support for it as well.
[1] https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html
The point of adding more undefined behavior for this case, or any case in general, is to provide optimization opportunities that do not require introducing changes to the syntax (such as additional type checking or analysis). That way a C++ compiler is welcome to provide debugging support and various checks when a program is compiled in debug mode, and then eliminate those checks and make very strong assumptions about the program's runtime behavior when a program is compiled with optimizations enabled.
This is in contraposition to OPs claim that "There is no "debug mode" for undefined behavior.". There absolutely is a debug mode and it absolutely can catch undefined behavior, and UBSan is an excellent tool for doing precisely what OP claimed is not permissible in C++.
https://blog.janestreet.com/what-is-gained-and-lost-with-63-...