Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

like image 823
Dan Avatar asked Jan 08 '21 21:01

Dan


People also ask

Can you add two characters in C?

How to append one string to the end of another. In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.

What happens if you add a char and int in C?

When you add a char to an int , the (p)r-value created is promoted to an int . Therefore what is printed is the int equivalent to the sum of the (usually) ASCII value + the int.

Can you add characters in C?

Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string. h is the header file required for string functions.


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
like image 140
Carl Norum Avatar answered Sep 23 '22 01:09

Carl Norum