Search code examples
ccpuinstruction-set

What is -(-128) for signed single byte char in C?


My little program:

#include <stdio.h>

int main() {
    signed char c = -128;
    c = -c;
    printf("%d", c);
    return 0;
}

print:

-128

Is minus (-) operator portable across CPU?


Solution

  • The operand of the unary minus first undergoes standard promitions, so it is of type int, which can represent the value -128. The result of the operation is the value 128, also of type int. The conversion from int to signed char, being a narrowing of signed types, is implementation-defined.

    (Your implementation seems to do a simple wrap-around: 125, 126, 127, -128, -127, ...)