2

I am using an assignment statement like: long long m = 2<<31;

Why this line gives warning " Signed shift result requires 34 bits to represent but, int only has 32 bits"? When I try to print m, output is 0.

When I use sizeof(long long) it says 8 bytes, i.e. 64 bits, much more than 32 bits. Then why it cannot accomodate?

Very much confused..please help.

Vibhav
  • 125
  • 7
  • 9
    2 is int. 2<<31 is integer overflow. You might want`2ULL`. – 273K Sep 03 '22 at 06:44
  • 2
    Unfortunately the `2` and the `31` are both `int`s , so the operation results in an `int`. The compiler doesn't care that you assign the result to a type large enough to store the intended result, that happens too late to be of any use. – user4581301 Sep 03 '22 at 06:50
  • 1
    Text doesn't match title, btw. Also, the size of integers is implementation-defined. – Ulrich Eckhardt Sep 03 '22 at 06:50
  • 2
    Does this answer your question? [How do I mute this error : "integer literal is too large to be represented in a signed integer type"](https://stackoverflow.com/questions/35136202/how-do-i-mute-this-error-integer-literal-is-too-large-to-be-represented-in-a) – Karl Knechtel Sep 03 '22 at 06:51
  • 2
    "When I use sizeof(long long) it says 8 bytes, i.e. 64 bits, much more than 32 bits. Then why it cannot accomodate?" It doesn't matter what the variable type is. There is already an **expression** `2<<31` that has to be evaluated first; the `2` and the `31` **have a type**, `int`; the `<<` operator produces a result **of that same type**, which does not accommodate the result value. – Karl Knechtel Sep 03 '22 at 06:52
  • When the compiler is working out `2 << 31` it doesn't say to itself 'well eventually this is going to be stored in a `long long` so I'll make an adjustment now'. No, as usual, the compiler does exactly what you tell it, even if in human terms it seems pretty dumb. – john Sep 03 '22 at 06:58
  • Computers can be stupid so fast that they fool you into thinking they are smart. – user4581301 Sep 04 '22 at 20:00
  • Thanks for the help..like all of you suggested above I should use the suffix ULL for integer 2, I am curious about what are the other such available options in C/C++ ? – Vibhav Sep 05 '22 at 04:26
  • 1
    [C Documentation](https://en.cppreference.com/w/c/language/integer_constant) and [C++ Documentation](https://en.cppreference.com/w/cpp/language/integer_literal) – user4581301 Sep 05 '22 at 05:03

0 Answers0