C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Integer overflow arithmetic with exceptions

From: Hans Åberg <haberg_1_at_[hidden]>
Date: Sat, 5 Apr 2025 18:04:33 +0200
I think of a simpler big num type primarily for avoiding having to keep track of overflow, suitable when one does heap allocations as in your example and does not need high performance (like in dynamic languages). With the fundamental arithmetic functions available, it would be good to have it in the language.

And where is this header available?


> On 5 Apr 2025, at 16:42, Tiago Freire <tmiguelf_at_[hidden]> wrote:
>
> Hi Hans,
> I think I'm starting to understand what you mean.
> My proposal does not introduce Big Number abstraction, although it is part of the motivation.
> One of the challenges to be able to create such type of abstractions is the lack of support in the language for arithmetic operations that preserve information when basic types would overflow. And although they have been staple in CPU design since as far as I’ve ever known CPUs, there is almost no way to access them in C++ other than “write your own assembly”, and there is no portal way to do it.
> The application of such arithmetic types goes beyond big number representations.
> This proposal only introduces the required arithmetic operations.
> Once available writing portable bignumber libraries will then be possible, and I would expect more of those to show up, altough it is not its sole application.
> As regarding the code “not compiling”, I haven’t put so much effort into creating a build system for it.
> The solution is header only (except for unit test), it has been tested in MSVC and gcc x86_64, it should compile with C++23, it is up to you to use it in your project and hook it up to your build system. Arm64 and Clang was not tested.
> From: Hans Åberg <haberg_1_at_[hidden]>
> Sent: Saturday, April 5, 2025 3:42:34 PM
> To: Tiago Freire <tmiguelf_at_[hidden]>
> Cc: std-proposals_at_[hidden] <std-proposals_at_[hidden]>
> Subject: Re: Integer overflow arithmetic with exceptions
> It would be good if your big num example would be a part of the standard in some form.
>
> One could add a word so that the std::vector part avoids heap allocations for smaller values, but that would be an optimization, not a part of the type semantics. It does not seem possible otherwise to avoid conditionals for a type that dynamically can change allocations, since if, say, adding two numbers, one would need to determine which functions to use. If using double dispatch instead, one cannot optimize away the function calls, which might not be good in this low-level programming.
>
> I have written a C++ wrap for multiprecision integer and rational numbers, if that would help. I could not compile your example, though. A working example for GCC or Clang on arm64 or x86_64 would help.

Received on 2025-04-05 16:04:49