faheel/BigInt

Declaration with initialisation of a BigInt with a string fails

faheel opened this issue · 1 comments

The following doesn't seem to work:

BigInt num = "12345678901234567890";

Generates the following error (using g++ version 7.x):

error: invalid conversion from ‘const char*’ to ‘const long long int&’ [-fpermissive]
     BigInt num = "12345678901234567890";
                  ^~~~~~~~~~~~~~~~~~~~~~

This error is caused because "12345678901234567890" is treated as a C string, which is of type const char *, which being a pointer (integer) is matched with the signature const long long&, but such a conversion is not allowed, hence the error.

The fix is simple: use the ""s operator to form a string literal from the C string. In other words, add an s after the string's closing quote:

BigInt num = "12345678901234567890"s;

One caveat though is that this only works in the std namespace. For a more general fix, you may use one of the following workarounds.

Other workarounds

  • Use the constructor:
BigInt num = BigInt("12345678901234567890");
  • Declare and initialise separately:
BigInt num;
num = "12345678901234567890";