bitwise shift confusion

why they print differently, both in clang and vs c++
t1= 0000000000000001; 1
t2= 1111111111111111; -1

1
2
3
4
5
6
7
8
9
10
  #include <iostream>
#include <bitset>

int main() {
  short t1 = 0b1000000000000000 >> 15;
  short t2 = -32768 >> 15;
  std::cout << "t1= " << std::bitset<16>(t1) << "; " << t1 << std::endl;
  std::cout << "t2= " << std::bitset<16>(t2) << "; " << t2 << std::endl;
}

-32768 is promoted to a signed int (a negative value).
Right-shift on signed integral types is an arithmetic right shift, which performs sign-extension.

Ideally, do not perform bit-wise shift operations on signed integer types.

I understand how t2 showed up, what I dont understand is t1 is supposed to be the same as t2, its signed and given the value of -32768, why the shift is normal instead of arithmetic?
It is implementation-defined whether the shift is arithmetic or logical. In general we avoid shifting signed values in C/C++.
C++17: The value of E1 >> E2 is E1 right-shifted E2 bit positions. ... If E1 has
a signed type and a negative value, the resulting value is implementation-defined.

C++20: E1 is right-shifted E2 bit positions. Right-shift on signed integral types is an arithmetic right shift, which performs sign-extension.
Topic archived. No new replies allowed.