gpt4 book ai didi

c - 在存在 unsigned int 和 signed int 的 C 表达式中,哪种类型将提升为哪种类型?

转载 作者:太空宇宙 更新时间:2023-11-04 00:01:16 27 4
gpt4 key购买 nike

我对 C 语言标准中的数据类型提升规则有疑问。C99 说:

C 整数提升还要求“如果一个 int 可以表示原始类型的所有值,则将该值转换为 int;否则,将其转换为 unsigned int。”

我的问题是如果 C 语言表达式中存在 unsigned intsigned int,哪种类型将被提升为哪种类型?

例如int 不能表示 unsigned int 的所有值(值大于 MAX_INT 值),而 unsigned int 不能表示-ve 值,那么在这种情况下什么类型被提升为什么?

最佳答案

我认为您混淆了两件事。 提升 是将 int/unsigned int 类型“更小”的整数类型的值转换为 int 或 unsigned int 的过程。规则的表述有些奇怪(主要是为了充分处理字符),但要确保保留值和符号。

然后是普通算术转换的不同概念,通过该概念将算术运算符的操作数转换为通用类型。如果操作数的类型小于 int,它首先提升操作数(为 int 或 unsigned),然后通过以下过程选择目标类型(对于整数类型,6.3.1.8/1)

If both operands have the same type, then no further conversion is needed.

Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.

Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.

Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

(请注意 ISTR,这些规则在 C89 和 C99 之间略有变化)

关于c - 在存在 unsigned int 和 signed int 的 C 表达式中,哪种类型将提升为哪种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42261899/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com