uint64_t x(1 << 35)
gives the output as 0
with a warning. What would the most appropriate to initialize such large values?
Asked
Active
Viewed 5,659 times
3

ForceBru
- 43,482
- 10
- 63
- 98

letsBeePolite
- 2,183
- 1
- 22
- 37
-
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
-
2How about `(static_cast
(1) << 35)` ? – Richard Critten Apr 17 '16 at 17:56 -
1In 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 Answers
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
- 400,186
- 35
- 402
- 621
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
- 231,907
- 34
- 361
- 483
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