简体   繁体   中英

(un)signed short int (C)

It has been established in another question on this website that there is no literal suffix for short in C and that one can do the following:

short Number = (short)1;

But what is the difference between casting it and not doing so:

short Number = 1;

Does it ever matter which you use and how does the compiler handle them differently?

There is no difference in effect of the implicit cast and the forced cast, the forced cast is largely "documentary" - it says "I did this deliberately" .

The explicit cast makes it clear to a potential maintainer, they the type is deliberately short and should not be changed to match the initialiser. It may also serve to silence compiler or static analysis tool warnings. However if you provide an initialiser that is too large for a short - it will silence any warning of that too.

The explicit cast is perhaps more useful in macro definitions such as:

#define DEFAULT_CONDITION ((short)1)

short condition = DEFAULT_CONDITION ;

The behavior of the code is the same in both cases.

But some code checkers/compilers could warn if you assign an int to a short (with an implicit conversion).

Most tools I know don't do that for literal values though. They check if the known literal actually fits into the smaller type.

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