Multiplying char and int together in C

Posted by teehoo on Stack Overflow See other posts from Stack Overflow or by teehoo
Published on 2010-04-16T00:06:51Z Indexed on 2010/04/16 0:13 UTC
Read the original article Hit count: 578

Filed under:
|
|
|
|

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?

© Stack Overflow or respective owner

Related posts about c

    Related posts about arithmetic