Adding two characters and assigning the result to an int in C

Viewed 62
int main(){

 char a = -5;
 char b = -6;
 int c = a+b;
 return 0;
}

I'm getting different results for the above code in different architectures, using gcc.

on x86 the variable c is properly sign extended and I get -11.

On some other architectures c is not sign extended, you get the result of a+b bit-casted to an int and I get 501.

Is this undefined behaviour?

1 Answers

char is sometimes an unsigned type. Use signed char or unsigned char if you need to be explicit about it. Adding a print to your program and compiling under both circumstances shows your behaviour:

$ make example && ./example
cc     example.c   -o example
-11

vs:

$ CFLAGS=-funsigned-char make example && ./example
cc -funsigned-char    example.c   -o example
501
Related