Search code examples
c++cbit-manipulationbit-shift

How compilers identify the length of byte shift operators


Consider the following line:

int mask = 1 << shift_amount;

we know that mask is 4 bytes because it was explicitly declared int, but this 1 that to be shifted has unknown length. If the compiler chose type as char it would be 8 bits, or it could be unsigned short with size 16 bits, so shifting result will really depend on the size of the compiler's decision about how to treat that 1. How does the compiler decide here? And is it safe to leave the code this way or should it instead be:

int flag = 1;

int mask = flag << shift_amount;


Solution

  • 1 is an int (typically 4 bytes). If you wanted it to be a type other than int you'd use a suffix, like 1L for long. For more details see https://en.cppreference.com/w/cpp/language/integer_literal.

    You can also use a cast like (long)1 or if you want a known fixed length, (int32_t)1.

    As Eric Postpischil points out in a comment, values smaller than int like (short)1 are not useful because the left-hand argument to << is promoted to int anyway.