Today I found the following:
#include <stdio.h>
int main(){
char x = 255;
int z = ((int)x)*2;
printf("%d\n", z); //prints -2
return 0;
}
So basically I'm getting an overflow because the size limit is determined by the operands on the right side of the = sign??
Why doesn't casting it to int before multiplying work?
In this case I'm using a char and int, but if I use "long" and "long long int" (c99), then I get similar behaviour. Is it generally advised against doing arithmetic with operands of different sizes?
char
can be either signed or unsigned, depending on your compiler.
In your case, it appears to be signed, and 255 is outside the range it can represent (likely, it can only represent numbers from -128 to 127).
So the problem occurs when you assign 255 to your char
variable - this results in an implementation-defined value, which in your case, appears to be -1.
When you multiply -1 by 2, you get -2. No mystery there. The cast to (int)
does nothing - types narrower than int
are always promoted to int
or unsigned int
before any calculations are done with them.