In this tutorial, you will learn how to determine whether the right shift operation in C for signed values is arithmetic or logical. You will understand the difference between these two types of shifts, explore how C handles them, and learn how to test this behavior on your system using simple C code.
What is a Right Shift?
A right shift moves the bits of a number to the right by a specified number of positions. For example:
int x = 16; // Binary: 00010000 int y = x >> 2; // Result: 00000100 (4 in decimal)
This operation drops the two rightmost bits and shifts in new bits on the left. But what those new bits are depends on the type of shift and whether the value is signed or unsigned.
Logical vs Arithmetic Right Shift
Arithmetic Right Shift: Preserves the sign bit. Negative numbers remain negative.
11110000 >> 2 = 11111100 (if arithmetic shift)
Logical Right Shift: Inserts zeros from the left.
11110000 >> 2 = 00111100 (if logical shift)
Important Note:
In C, right-shifting a signed negative integer is implementation-defined. This means different compilers or systems might behave differently. However, most modern compilers (like GCC and Clang on x86) perform an arithmetic shift for signed integers.
For unsigned integers, right shift is always logical.
How to Check: A Simple Test Program
Here’s a quick way to test what your compiler does when right-shifting a signed negative number.
#include <stdio.h> int main() { int num = -4; // Example negative number int result = num >> 1; printf("Original number: %d\n", num); printf("After right shift: %d\n", result); if (result < 0) printf("Right shift is Arithmetic (sign bit preserved)\n"); else printf("Right shift is Logical (zeros filled in)\n"); return 0; }
Optional: Add Bit-Level Output
To visualize the actual bit shift, you can include this helper function:
void print_binary(int n) { for (int i = sizeof(int) * 8 - 1; i >= 0; i--) { printf("%d", (n >> i) & 1); } printf("\n"); }
Then modify your main function:
print_binary(num); print_binary(result);
What to Look For:
- If the result is -2, your system uses arithmetic shift.
- If the result is a large positive number, your system might be using a logical shift (rare for signed values).
Example Output (on most systems):
Original number: -4 After right shift: -2 Right shift is Arithmetic (sign bit preserved)
Best Practices
- Avoid relying on right shifts of signed negatives unless you’re sure of compiler behavior.
- For guaranteed logical shift on signed values:
- For arithmetic shift, use signed values and verify behavior during compilation.
unsigned int val = (unsigned int)signed_val; unsigned int result = val >> 1;
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Watch Advanced C Programming Videos
- Apply for C Internship
- Check C Books
- Check Computer Science Books
- Apply for Computer Science Internship