Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 21994

Subtracting chars doesn't overflow when it should [duplicate]

$
0
0

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?


Viewing all articles
Browse latest Browse all 21994

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>