0

I have two variables a and b and are declared and assigned as follows:

UInt64 a = (UInt64)4294967295 * 3;
UInt64 b = 4294967295 * 3;

When I print them a contains 12884901885 and b contains 4294967295.

Why do I have to cast the number with UInt64 to store such a large value ?

Thanks

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
takanoha
  • 183
  • 4
  • 17
  • 1
    Use LL suffix on the numbers. https://stackoverflow.com/questions/8809292/ull-suffix-on-a-numeric-literal – Michael Chourdakis Sep 26 '19 at 23:38
  • 3
    The result of the multiplication is the type of the operands, (or `int`). – Ben Voigt Sep 26 '19 at 23:38
  • Are you familiar with the following nuance: `float x = 1/2;` results in `x == 0.0`, while `float x = (float)1/2;` results in `x == 0.5`? – JaMiT Sep 26 '19 at 23:57
  • One thing you could do is type `auto b = 4294967295;`. Hover over the b variable and it will tell you that it is a variable of `unsigned long`. Which is a type that's big enough to represent that value, takes 32 bits of storage. Multiply it by 3 and you have a value that no longer fits in 32 bits. The wise men decided that this not something they have to warn you about. Yes, not very wise, they didn't have a lot of memory back in the 1970s. – Hans Passant Sep 27 '19 at 00:25

1 Answers1

1

you need to append 'ULL' (a.k.a. Unsigned Long Long) to the constant to indicate it should be considered to be a 64bit value.

UInt64 b = 4294967295ULL * 3;
robthebloke
  • 9,331
  • 9
  • 12
  • This explains how to *solve* the problem, but does not explain the *reason why* the original code doesn't work. You should expand on your answer accordingly. – Remy Lebeau Sep 27 '19 at 00:45