This question already has an answer here:
I was implementing the library function strcmp, which should return, depending on the input, less than 0 when the first char array is smaller, greater when it is bigger and 0 when the arrays are equal. A clever trick I encountered was to find the first index where there is a difference and subtract the characters at the index. I thought that this would break since we are subtracting characters which could cause them to overflow, so I tested it with this program and it does in fact work.
int res(){
char a = -128;
char b = 15;
return a-b;
}
output: -143
So my question is why does this work. Is char
always casted to integer before arithmetic operations or is the compiler just being smart?