9
#include <stdio.h>
#include <stdint.h>

int main(){
    uint64_t a = 1 << 63;
    /* do some thing */
    return 0;
}

$ gcc -Wall -Wextra -std=c99 test.c -o test  
warning: left shift count >= width of type [-Wshift-count-overflow]

Q: uint64_t should have 64 bits width, why the left shift operation overflows?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Ruby Sapphire
  • 325
  • 3
  • 4
  • 9
  • 1 is an `int` literal. Using `1ULL << 63` instead – phuclv Mar 28 '17 at 04:14
  • @LưuVĩnhPhúc C specifies `1` as an _integer constant_ of type `int`. The only _literals_ specified in C are _string literals_ and _compound literals_. `1` is neither of those 2 literals. – chux - Reinstate Monica Mar 28 '17 at 04:17
  • 1
    "why the left shift operation overflows?" --> which happens first: `1 << 63` or its assignment to `uint64_t a`? Since `1 << 63` occurs first, the type it is assigned to is irrelevant to `1 << 63` evaluation. – chux - Reinstate Monica Mar 28 '17 at 04:24

1 Answers1

11

1 is an int which is either only 32 bits on your platform, or it could be 64 bits but signed.

Use (uint64_t)1 << 63 to cast 1 to 64-bit unsigned integer first. (Or ((uint64_t)1) << 63 if you prefer)

user253751
  • 57,427
  • 7
  • 48
  • 90