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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With