11

What is the result of number when it is left shifted by -1 in C programming using the left shift operator?

e.g.:

23 << -1 
10
  • 2
    left shifting with -1 looks like a right shifting with 1 Commented Jul 21, 2015 at 19:37
  • @adricadar: Looks like (and I sometimes whish it was), but: Fundamentally wrong. Commented Jul 21, 2015 at 19:40
  • Note: As OP said "number", there is another restriction: "Each of the operands shall have integer type". Commented Jul 21, 2015 at 19:55
  • 1
    @MartinJames: A negative constant shift might areise from macros. But more important are run-time yielded negative shifts, e.g. during normatization of software-floating point arithmetic. Commented Jul 21, 2015 at 20:33
  • 1
    @MartinJames: If we close all questions about UB, we could very well close all C questions. The few non-UB questions would be acceptable "collateral damage". Commented Jul 21, 2015 at 20:35

3 Answers 3

9

From the C11 standard 6.5.7p3 (for former versions it is basically the same):

"If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined."

IOW: undefined behaviour. Prepare for nasal demons.

Briefly: Do not

Caution: While many programmers are aware of that and avoid negative shift counts, it is often ignored that also counts >= the bit-size of the value are also undefined. This makes something like ((unsigned int)1 << 32) - 1 actually undefined if unsigned int has 32 bits or less. For signed values things become more complicated due to the sign (thanks @chux for pointing me at that). This is a common pitfall. For some implementations, different results for constant expressions (compile-time evaluated) and run-time evaluation might occur.

Sign up to request clarification or add additional context in comments.

2 Comments

Is not ((int)1 << 31) - 1 also undefined if int has 32 bits or less?
@chux: Updated. Thank you!
1

As Olaf said in his answer, left shifting by a negative number is undefined.

In fact, gcc will give a warning if you attempt shift in either direction by a negative number.

1 Comment

"... gcc will give a warning ...": but only if it can detect it compile time, i.e. if the shift count is a constant as in the question.
0

Bitwise Left Shift Operator in C:

  1. Bit Pattern of the data can be shifted by specified number of Positions to Left
  2. When Data is Shifted Left , trailing zero’s are filled with zero.
  3. Left shift Operator is Binary Operator [Bi – two]
  4. Binary means , Operator that require two arguments!

Table

Syntax:

**[variable]<<[number of places]** 

If Number of Places become negative, it will be undefined

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.