简体   繁体   中英

typecasting long to int and short in C

long x = <some value>
int y = <some value>

I want to subtract y from x , which of the following will give me different or same results

 x = (int)x - y;

 x = x-y

 x = short(x) - short(y)

The type long is "bigger" than int . Smaller types can be automatically casted to bigger types. So, this code:

someLongNumber + someIntNumber

is basically equal to

someLongNumber + (long)someIntNumber

So the output will be long . You don't have to cast if you want to place the result in x . However, if you want to place it in y , you must cast the x operand to int ( (int)x ), or the whole operation ( (int)(x - y) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM