整形提升这部分内容,其实C++11 ISO文档里介绍的已经很详细了,但还是容易忘记细节。
相关内容在ISO文档的4.5章节,这里就不重复粘贴上来了。
其实所有算术转换的基本原则都是保留精度的前提下做类型提升。
比如char提升成int。目标类型的优先级也是从小到大,int, unsigned int, long int, unsigned long int, long long int, unsigned long long int。一般是这个顺序。
那么如果signed和unsigned混用会怎么样?这个是个特例,会有精度缺失的问题。
关于这部分内容可以在C99 ISO文档的6.3.1.3章节找到。
其中第二条:
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or
subtracting one more than the maximum value that can be represented in the new type
until the value is in the range of the new type.
这条说的很清楚,混用unsigned和signed,signed会被强制转换成unsigned类型,由于两种类型边界不同,因此值就有不同。
所以,如果不得不混用这两种类型的话,最好先手动做强制转换。以免出现差错。
另外,C++11文档和C99文档其实有些互补,以后也别只盯着C++11文档,C99也得熟悉,算是一点经验吧。