3

uint64_t x(1 << 35) gives the output as 0 with a warning. What would the most appropriate to initialize such large values?

ForceBru
  • 41,233
  • 10
  • 61
  • 89
letsBeePolite
  • 2,063
  • 1
  • 15
  • 34
  • Use a literal of the right type, the expression `1ULL << 35` won't overflow because the left hand side is a large enough type – Ben Voigt Apr 17 '16 at 17:55
  • 2
    How about `(static_cast(1) << 35)` ? – Richard Critten Apr 17 '16 at 17:56
  • 1
    In C++11 and later can also define [new literals for the types in ``](https://stackoverflow.com/questions/36406333/fixed-width-integer-literals-in-c) which you can use to avoid such problems. – mceo Apr 17 '16 at 18:10

4 Answers4

9

It's because 1 << 35 is an operation using int. If you want 64-bit types then use 1ULL << 35 to make sure it's an operation using unsigned long long (which is guaranteed to be at least 64 bits).

Some programmer dude
  • 380,411
  • 33
  • 383
  • 585
4
auto x = std::uint64_t(1) << 35;
Richard Hodges
  • 66,334
  • 6
  • 85
  • 131
2

The problem you have is that the compile time evaluate constant expression 1 << 35 is performed with int types. So it's likely you are overflowing that type and the behaviour is undefined!

The simplest fix is to use 1ULL << 35. An unsigned long long literal must be at least 64 bits.

Bathsheba
  • 227,678
  • 33
  • 352
  • 470
1
uint64_t x = 1000000000ull;

The ull marks the value as unsigned long long

int64_t y = 1000000000ll;

The same with a normal long long.

uint64_t x2 = (1ull << 35ull);

Simply add ull at the end of your number.

tistCoder
  • 309
  • 3
  • 12