0

I am trying to add two numbers in C. My code is

#define type unsigned
type add(type a, type b) {
    return a + b;
}

Code corresponding to above code in assembly makes use of a single add instruction (https://godbolt.org/ & ARM GCC 8.3.1). However when I changed the type to unsigned long long, code was bit obfuscated to understand; But, I believe it makes use of some ldm and then asks hardware to add complete vectors (or arrays). Similarly my next question was: is it possible to add two numbers where digits count in each number will be in the order of 1000s? It isn't hard to design a function and make it work, and I found many codes on internet which do this. But, I think compiler writes better code than us,

  • so are there any gcc built-in functions which can do this job?
  • In fact, does gcc provide such functions for all the 5 integer arithmetic operations?
Vishwajith.K
  • 85
  • 1
  • 10
  • 2
    As far as I know, the answer is no. You might want to just use a language like Ruby or Python that already supports arbitrarily big integers. Or use the [GMP library](https://gmplib.org/). – David Grayson Apr 18 '21 at 17:26
  • 2
    clang has such a feature, see https://stackoverflow.com/questions/61411865/how-do-you-use-clangs-new-custom-size-int-feature, but it has issues. (1) You have to choose the size at compile time; (2) division and mod aren't implemented for arbitrarily large sizes (3) the code it generates is rather naive (always fully unrolled and inlined), so it is often worse than hand-tuned code from gmp or the like. – Nate Eldredge Apr 18 '21 at 17:35
  • 2
    "But, I think compiler writes better code than us": True in many cases, but arbitrary-precision arithmetic tends to be an exception, as it relies on machine constructs (add with carry, etc) that don't exist in C and that the compiler isn't used to trying to optimize. – Nate Eldredge Apr 18 '21 at 17:37

1 Answers1

3

No, there is no compiler support in GCC for arbitrary-precision arithmetic. You would need to use a library like GMP. If you can use C++ instead of C, you can get a more "natural" API (with arithmetic operators, etc.) by using a library like Boost Multiprecision.

GCC does support, as an extension, the types __int128 and unsigned __int128, which can be used like any other integral type, but these only provide capacity for 38 decimal digits.

Edit: Also, as an aside, don't use macros (like #define type unsigned) to rename types. Instead this should be written with the typedef keyword like so: typedef unsigned type;

Ray Hamel
  • 1,289
  • 6
  • 16