Left shifting or Right shifting a integer with negative number, is it a defined behaviors?

88 Views Asked by At

I tried the below code and in both the cases i.e. (left shift and right shift) i got the output as 0

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int a=20;

    a=a<<-1;
    cout<<a;
    int x=20;
    x=x>>-1;
    cout<<x;
    return 0;
}
1

There are 1 best solutions below

0
dbush On

Shifting by a negative value triggers undefined behavior in your code. This is specified in section 8.8p1 of the C++ standard regarding the bitwise shift operators:

The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand