Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 632
gavenkoa Avatar asked Jul 04 '13 12:07

gavenkoa


People also ask

What is the use of signed char in C?

You would use a signed char when you need to represent a quantity in the range [-128, 127] and you can't (for whatever reason) spare more than a single byte to do it.

What is unsigned char * in C?

unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255.

How is signed char represented in memory?

For example, if we want to store char 'A' in computer, the corresponding ASCII value will be stored in computer. ASCII value for capital A is 65. To store character value, computer will allocate 1 byte (8 bit) memory. 65 will converted into binary form which is (1000001) 2.


1 Answers

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, ...)

like image 107
Kerrek SB Avatar answered Sep 20 '22 20:09

Kerrek SB