-2

Why does 1<<31 print 18446744071562067968 as output when we run the following code?

#include<iostream>
using namespace std;

int main(){
    unsigned long long int i = 1<<31;
    cout<<i; // this prints 18446744071562067968
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
iron_man
  • 57
  • 5
  • 3
    `1` is an `int`, not an `unsigned long long`. –  Dec 19 '17 at 22:04
  • 2
    Try `unsigned long long int i = 1UL << 31;` – i486 Dec 19 '17 at 22:04
  • 3
    You should include what you expect in the question, for the sake of completeness. These downvotes seem very unnecessary to me though. Even though I have a decent amount of C++ experience, it took me a minute to realize what was going on (especially having mostly programmed in a language for a while where the static type inference is done in a very different way and would give a different result). – David Young Dec 19 '17 at 22:06
  • 1
    Downvoted for lack of research effort. Googling either "site:stackoverflow.com "1 << 31"" or "site:stackoverflow.com "18446744071562067968"" would have easily given you the solution, even earlier if you include "c++". – Baum mit Augen Dec 19 '17 at 22:24

1 Answers1

16

1 is a signed int, which on your system is 32 bits. 1 << 31 results in overflow, and is a negative number (0x80000000). This, when converted to a 64 bit unsigned long long is then sign extended to 64 bits before being converted to the ULL value, which is 0xFFFFFFFF80000000, or the large decimal number you see.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56