首页 > 解决方案 > 带括号的子表达式的类型提升规则是什么?

问题描述

假设一个整数表达式由多个无符号整数类型uint16_tuint32_t. 该表达式包含一个带括号的子表达式,其中所有元素的类型都是uint16_t

uint32_t括号内的子表达式中的元素是否应该在评估子表达式之前被提升?

例如:

#include <stdint.h>
#include <stdio.h>

int main(void)
{
    uint16_t a16 = 0x2000;
    uint16_t b16 = 0x3000;
    uint32_t c32 = 0x00000001;
    uint32_t d32;

    // Should (a16 * b16) be evaluated to 0x06000000, or to 0x0000?
    // Should d32 be evaluated to 0x06000001, or to 0x00000001?
    d32 = c32 + (a16 * b16);

    printf("d32=0x%08x\n", d32);

    return 0;
}

在ideone在线编译器中尝试这个建议a16并在乘法之前b16提升。uint32_t这是 C 标准规定的吗?为什么不在uint16_t括号内求值?

标签: ctypesinteger-promotiontype-promotion

解决方案


在乘法之前,所有比窄的类型int都被提升为一个。int

因此,如果您有 32 位 2 的补码int,那么结果实际上是两种int32_t类型的乘积。

表达式中的括号对这种隐式类型转换或最终结果都没有影响。


推荐阅读