letsBeePolite
letsBeePolite

Reputation: 2251

How to initialize uint64_t in C++11

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

Upvotes: 3

Views: 6679

Answers (4)

tistCoder
tistCoder

Reputation: 309

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.

Upvotes: 1

Richard Hodges
Richard Hodges

Reputation: 69892

auto x = std::uint64_t(1) << 35;

Upvotes: 4

Bathsheba
Bathsheba

Reputation: 234715

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.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409196

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).

Upvotes: 9

Related Questions