Tre*_*key 4 c c++ int char integer-promotion
我向我的一位同事发了言,其中:
"字符在C表达式中自动提升为整数,这对性能很好,因为CPU的自然字大小最快.
我认为由于char的排名,在标准的某处陈述了char促销行为.
这是我回复的回复:
"字符不是默认提升为整数.寄存器大小为32位,但一行中的多个字节值可以作为编译器实现打包到单个寄存器中.这并不总是预测性的.唯一可以验证自动升级的时间是因为C标准在调用堆栈内存中正式需要32位值时类型被传递到调用堆栈中,因为C标准在调用堆栈内存中需要32位值.大量的CPU架构优化了非32位值的汇编调用,所以没有在这种情况下,可以对CPU或编译器做出假设."
我不确定谁是对的,还有什么可以相信的.有什么事实?
字符在C表达式中自动提升为整数
对,他们是.C99第6.3.1.8节,通常的算术转换:
许多期望算术类型操作数的运算符会以类似的方式导致转换并产生结果类型.目的是确定操作数和结果的通用实数类型.对于指定的操作数,每个操作数在不更改类型域的情况下转换为其对应的实类型是公共实类型的类型.除非另有明确说明,否则公共实类型也是结果的对应实数类型,如果它们相同则其类型域是操作数的类型域,否则是复数.这种模式称为通常的算术转换:
- 首先,如果任一操作数的相应实数类型是long double,则另一个操作数在不改变类型域的情况下被转换为对应的实类型为long double的类型.
- 否则,如果任一操作数的对应实数类型为double,则将另一个操作数转换为对应的实类型为double的类型,而不更改类型域.
- 否则,如果任一操作数的相应实数类型为float,则另一个操作数在不更改类型域的情况下转换为对应的实类型为float的类型.62)
- 否则,将对两个操作数执行整数提升.然后将以下规则应用于提升的操作数:
- 如果两个操作数具有相同的类型,则不需要进一步转换.
- 否则,如果两个操作数都具有有符号整数类型或两者都具有无符号整数类型,则具有较小整数转换等级类型的操作数将转换为具有更高等级的操作数的类型.
- 否则,如果具有无符号整数类型的操作数的秩大于或等于另一个操作数的类型的秩,则具有有符号整数类型的操作数将转换为具有无符号整数类型的操作数的类型.
- 否则,如果带有符号整数类型的操作数的类型可以表示具有无符号整数类型的操作数类型的所有值,则具有无符号整数类型的操作数将转换为带有符号整数类型的操作数的类型.
- 否则,两个操作数都转换为无符号整数类型,对应于带有符号整数类型的操作数的类型.
整数促销在第6.3.1.1.2节中描述:
如果可以使用int或unsigned int,则可以在表达式中使用以下内容:
- An object or expression with an integer type whose integer conversion rank is less than or equal to the rank of int and unsigned int.
- A bit-field of type _Bool, int, signed int, or unsigned int
If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanges by the integer promotions.
The rank of a char is less than or equal to that of an int, so char is included in here.
(As a footnote, it is mentioned that integer promotions are only applied as part of the usual arithmetic conversions, to certain argument expressions, to the operands of the unary +, - and ~, and to both operands of the shift operators).
如注释中所述,还对函数调用参数执行整数提升.