试图了解标准中的语法:
6.3.1.3有符号和无符号整数
- 将具有整数类型的值转换为_Bool以外的其他整数类型时,如果该值可以用新类型表示,则该值不变。
- 否则,如果新类型是无符号的,则通过重复添加或减去比新类型可表示的最大值多一个值来转换值,直到该值在新类型的范围内为止。
- Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
Note section 2, which means that casting int to unsigned int is performed by adding UINT_MAX + 1 to the value in the int.
Which is discussed for example in those two discussions:
Can a C compiler change bit representation when casting signed to unsigned?
Signed to unsigned conversion in C - is it always safe?
Well, since UINT_MAX + 1 is always promised to be zero (/sf/answers/1042941091/) section 2 can be read as:
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting zero until the value is in the range of the new type.
Which makes no sense to me, since adding zero change nothing. Is my english interpretation is broken? What am I missing here?
- 否则,如果新类型是无符号的,则通过重复添加或减去比新类型可表示的最大值多一个值来转换值,直到该值在新类型的范围内为止。
在本文中,“加或减”是指对数学值进行运算,而不是使用C +和-运算符对C值进行运算。
例如,如果起始值-42和UINT_MAX是65535,则结果为-42 + 65536,或65494。该数学值在的范围内,得出unsigned intC值为65494U。
的确,对C表达式求值的结果UINT_MAX + 1为零。这就是为什么该标准所指的是“比可以在新类型中表示的最大值多一个” UINT_MAX + 1。(诚然,它可以说得更清楚一点。)
| 归档时间: |
|
| 查看次数: |
117 次 |
| 最近记录: |