0
int main(){
    unsigned *dp;
    char *sp;
    *dp = *sp;
    return 0;
}

I don't understand why I got movsbl rather than movzbl while converting a char type to unsigned. Could someone kindly explain? Thx in advance!

Extra: Compiled code:

    call    __main
    movsbl  0, %eax
    movl    %eax, 0
    movl    $0, %eax
    addq    $40, %rsp
    ret
HelloWorld
  • 21
  • 3
  • Does [this](https://stackoverflow.com/a/7861177/7582247) answer your question? – Ted Lyngmo Jan 24 '22 at 03:35
  • See [integer promotions](https://en.cppreference.com/w/c/language/conversion). Presumably `char` is signed on your system. It has lower rank than `int`, so `*sp` is promoted to `int` before assigning to `*dp`, and that means sign extension. – Nate Eldredge Jan 24 '22 at 03:36
  • @TedLyngmo my question is why isn't zero extend – HelloWorld Jan 24 '22 at 03:53
  • @NateEldredge why isn't zero extend – HelloWorld Jan 24 '22 at 03:54
  • @HelloWorld: Zero extension would give the wrong result. If `*sp` had the value `-1` (i.e. `0xff` on a typical machine), then `*sp` gets promoted to `int`, the int `-1`. You are then converting `-1` to unsigned, which is defined to have wrap-around two's-complement behavior. The result assigned to `*dp` must be `0xffffffff` (assuming 32-bit `unsigned int`). Zero extension would yield `0x000000ff` in that case, which is wrong. – Nate Eldredge Jan 24 '22 at 04:16
  • @NateEldredge yes, 0xffffffff = -1, but why isn't the expected value equle to 1 since the destination type is unsigned? – HelloWorld Jan 24 '22 at 04:45
  • @HelloWorld: Are you thinking that converting signed to unsigned should take the absolute value? It doesn't. It wraps around mod 2^32 or whatever the maximum value of `unsigned` is. See C17 6.3.1.3p2. On a two's-complement machine this reduces to "use the same bits and treat them as an `unsigned`". – Nate Eldredge Jan 24 '22 at 04:56
  • @NateEldredge I see, thx! – HelloWorld Jan 24 '22 at 05:31
  • _"my question is why isn't zero extend"_ - I got that and thought it was answered in the answers I linked to, but @NateEldredge seems to have done a better job explaining it :-) – Ted Lyngmo Jan 24 '22 at 10:10

0 Answers0