在存在 unsigned int 和signed int 的 C 表达式中,哪种类型将提升为哪种类型?
我对C语言标准中的数据类型提升规则有疑问。 C99 规定:
C 整数提升还要求“如果 int 可以表示原始类型的所有值,则将该值转换为 int;否则,将其转换为无符号 int。”
我的问题是,如果存在 unsigned int
和 signed int
的 C 语言表达式,哪种类型将提升为哪种类型?
例如,int
无法表示 unsigned int
的所有值(大于 MAX_INT
值的值),而 unsigned int
则不能代表 -ve 值,那么在这种情况下什么类型会提升为什么?
I have a query about data type promotion rules in C language standard.
The C99 says that:
C integer promotions also require that "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."
My questions is in case of a C language expression where unsigned int
and signed int
are present, which type will be promoted to what type?
E.g. int
cannot represent all the values of the unsigned int
(values larger than MAX_INT
values) whereas unsigned int
cannot represent the -ve values, so what type is promoted to what in such cases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你混淆了两件事。 提升是将比 int/unsigned int “小的”整数类型的值转换为 int 或 unsigned int 的过程。这些规则的表达有些奇怪(主要是为了充分处理字符),但确保值和符号得到保留。
然后是普通算术转换的不同概念,通过它可以将算术运算符的操作数转换为公共类型。首先,如果操作数的类型小于 int,则将其提升为 int 或 unsigned,然后通过以下过程选择目标类型(对于整数类型,6.3.1.8/1)
(请注意 ISTR,这些规则在 C89 和 C99 之间略有变化)
I think you are confusing two things. Promotion is the process by which values of integer type "smaller" that int/unsigned int are converted either to int or unsigned int. The rules are expressed somewhat strangely (mostly for the benefit of handling adequately char) but ensure that value and sign are conserved.
Then there is the different concept of usual arithmetic conversion by which operands of arithmetic operators are converted to a common type. It begins by promoting the operand (to either int or unsigned) if they are of a type smaller than int and then choosing a target type by the following process (for integer types, 6.3.1.8/1)
(Note that ISTR that those rules have changed slightly between C89 and C99)
我认为以下内容可以回答您的问题:
I think the following answers your question: