Search code examples
cbit-shift

Explanation for equivalent looking statements returning different results after bitshift


Looking for an understanding of what is happening here as both statements appear the same.

So while the c >> 1 output is what I was expecting, shifting the wrapped uint in-place changes the result.

#include <stdio.h>
#include <stdint.h>

int main() {
    uint16_t a, b, c;
    a = 20180;
    b = 4106;
    c = b - a;
    printf("%hu\n", c >> 1);
    printf("%hu\n", (b - a) >> 1);
    return 0;
}

This prints:

24731

57499

What causes this behaviour?

Thanks.


Solution

  • The "in-place" operation promotes a and b to int, and the result will also be an int that you then shift. In your assignment of c = b - a, the operation is first promoted to int operation, executed, then type casted back to uint (to be set in c). The keyword to search for is "integer promotion"