0

This seems like it should be simple but it doesn't seem to be. I know I can define a constant by using

#define magicNumber 20

But in my class I need to multiply and divide by 2 large numbers over and over and was trying to figure out the best way. I can't just use

#define magicNumber1 10000000000
#define magicNumber2 100000000000000000000

I need something like

mpz_t magicNumber1;
mpz_init_set_str(magicNumber1,"10000000000",10);
mpz_t magicNumber2;
mpz_init_set_str(magicNumber2,"100000000000000000000",10);

and these 2 values can be used by my class over and over without reinitializing them. consteval or constexpr seem like they should be able to set up these static values but I can't seem to figure out how to do it.

  • 1
    Since IIRC `gmp` is a C library, it cannot be used in `constexpr` or `consteval` contexts. You can have a `static const` member in your class though, and it will be initialized only once in a program. If you have access to C++17, make that a `static inline const` member. – Fatih BAKIR Mar 25 '22 at 03:32
  • using C++20 so will look that up thanks – Matthew Cornelisse Mar 25 '22 at 03:41
  • 1
    Declare magicNumber1 as a global variable, and initialize it early during your program? Easier, use `mpz_class magicNumber1(...)`. The "constant" in your title seems misleading, from what I understand you want to construct it only once, but you don't care if that's at runtime. – Marc Glisse Mar 25 '22 at 07:14
  • 1
    preprocessed would be ideal for the sake of knowing how that works but run time works also. But both don't seem obvious in c++ since I can't just add a script after my class definition that will run to set the values(or at least i cant figure out how) – Matthew Cornelisse Mar 25 '22 at 10:39
  • 1
    I don't get it, why is it so important that your 2 numbers are macro-defined constants? Is it because of performance, because you are emplying them in artihmetic many times over? If so, then if possible you should consider using GMP `mpn_` [low-level functions](https://gmplib.org/manual/Low_002dlevel-Functions) directly, because you know what the signs of your constants are, and you'll save big time of `mpz_` routines for example deciding what the signs of the operands are. This should save much more processing than having a constant in your code be stored in a variable instead of literal. – Arc Mar 25 '22 at 17:46

0 Answers0