Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

negating characters in C

Tags:

c

Is this undefined behavior? It prints -128 as the result:

#include<stdio.h>
int main()
{
    char i=-128;
    i=-i;
    printf("%d",i);
}

Please explain.

like image 866
cdummy Avatar asked Jun 15 '12 21:06

cdummy


People also ask

Can a character be negative in C?

chars in 'C' are used to represent characters. Numbers representing characters in all code pages are always positive.

What is an unsigned char?

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.


2 Answers

The two's complement of -128 in an 8-bit signed value is -128.

Look at the binary values:

Original value: 10000000

Complement: 01111111

Increment: 10000000

like image 146
Fred Larson Avatar answered Sep 24 '22 07:09

Fred Larson


This is not undefined behavior. Assuming type char is signed in your platform, it is implementation defined behavior. (C99, 6.3.1.3p3)

i = -i;

the i in -i is first promoted to int, so -i is 128 and then 128 is converted to char by the integer conversions.

Here is the paragraph of the Standard that says the conversion of 128 to char is implementation defined:

(C99, 6.3.1.3p3) Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

EDIT: while it is implementation defined, there is a common implementation behavior between most implementations. Here is what gcc (and most other compilers do) documents to do:

For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type; no signal is raised

http://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html

Note that not all compilers behave this way. Some (DSP) compilers just saturate. In this case (and still assuming a signed char), after i = -i; the value of i would be 127.

like image 37
ouah Avatar answered Sep 22 '22 07:09

ouah