type promotion in C

偶尔善良 提交于 2019-11-30 20:30:57

The C standard explains this quite clearly (§6.5.6 Additive Operators):

If both operands have arithmetic type, the usual arithmetic conversions are performed on them.

(§6.3.1.8 Usual Arithmetic Conversions):

... the integer promotions are performed on both operands.

(§6.3.1.1 Boolean, characters, and integers):

If an int can represent all values of the original type, the value is converted to an int; ... These are called the integer promotions. All other types are unchanged by the integer promotions.

Since int can represent all values of uint16_t on your platform, a and b are converted to int before the subtraction is performed. The result has type int, and is passed to printf as an int. You have specified the %u formatter with an int argument; strictly speaking this invokes undefined behavior, but on your platform the int argument is interpreted as it's twos-complement representation, and that is printed.

If you throw away the top-end bits of a number (by the explicit cast to a 16 bit unsigned integer) then you're going to have a result that is smaller (within the range of 0 and 2^16-1) than before.

unwind

C promotes the arguments to unsigned int before doing the subtraction. This is standard behavior.

See, for instance, In a C expression where unsigned int and signed int are present, which type will be promoted to what type? for details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!