I know there are many topics on this subject but none of them helped me to fix my problem. I work on Code::Blocks (with the option -std=c99 in "Properties>Project Build Options>Compiler Settings>Other Options") and the following code doesn't give the expected output:
long long val=1<<33;
printf("value: %llu",val);
In fact I obtain "value: 0" in the terminal. How can I fix that problem?
When I write 30 instead of 33 (so val is an integer), I get the rigth answer. I have also tried %lld but that does not help.
Since you haven't qualified the literals 1 and 33 in any way, 1<<33
will have an int
as its type. If int
is 32 bit (very common on compilers targeting 64 bit) then this expression will yield undefined behaviour.
A simple fix would be to write 1LL << 33
. 1LL
is a long long
, and 33 will be promoted to that type too. The C++ standard guarantees that long long
is at least 64 bits.
In many ways though I prefer static_cast<std::int64_t>(1) << 33
.