评估`int x = -2147483648`会发生什么? [英] What happens when evaluating `int x = -2147483648`?

查看:115
本文介绍了评估`int x = -2147483648`会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

评估时会发生什么

int x = -2147483648

?

  1. 在评估-2147483648时,2147483648是一个整数类型,其long类型不是int,因此评估-2147483648的结果-2147483648是long类型,而不是int.

  1. When evaluating -2147483648, 2147483648 is a integer constant which has long type not int, so the result -2147483648 of evaluating -2147483648 is of type long, not int.

当评估赋值"int x = ..."时,RHS是long类型的值-2147483648,该值在x类型的int范围内.值-2147483648是否会隐式地从long转换为int,并且转换将保持值-2147483648不变?

When evaluating the assignment "int x = ...", the RHS is value -2147483648 of long type, which is in the range of x's type int. Will value -2147483648 be implicitly converted from long to int, and the conversion keep the value -2147483648 unchanged?

谢谢.

推荐答案

此答案假定C实现使用32位int和64位long.

This answer presumes the C implementation uses a 32-bit int and a 64-bit long.

C 2018 6.4.4.1说:整数常量的类型是相应列表中可以表示其值的列表中的第一个."在下面的表中,没有后缀的十进制常数条目包含列表intlong intlong long int.由于long int是可以表示2,147,483,648的那些中的第一个,所以2147483648具有类型long int.

C 2018 6.4.4.1 says "The type of an integer constant is the first of the corresponding list in which its value can be represented." In the table that follows, the entry for decimal constants with no suffix contains the list int, long int, long long int. Since a long int is the first of those that can represent 2,147,483,648, 2147483648 has the type long int.

根据6.5.3.3 3,-的结果为提升的类型.整数提升(6.3.1.1 2)对long int无效.所以-2147483648的类型是long int.

Per 6.5.3.3 3, the result of - is the promoted type. The integer promotions (6.3.1.1 2) have no effect on long int. So the type of -2147483648 is long int.

根据6.7.9 11,初始化程序的值将按照简单分配的方式进行转换.根据6.5.16.1 2和6.5.16 3,该值将转换为左值转换后要分配的对象的类型.也就是说,对于分配给int对象的类型,其类型为int值.

Per 6.7.9 11, the value of the initializer is converted as in simple assignment. Per 6.5.16.1 2 and 6.5.16 3, the value is converted to the type of the object being assigned would have after lvalue conversion. That is, for an assignment to an int object, the type is an int value.

根据6.3.1.3 1,将整数类型的值转换为另一整数类型时,如果新类型可以表示该值,则该值不变.由于int可以表示−2,147,483,648,因此它保持不变.

Per 6.3.1.3 1, when converting a value of integer type to another integer type, if the new type can represent the value, it is unchanged. Since int can represent −2,147,483,648, it is unchanged.

因此,int x = -2147483648;的结果是x被初始化为值-2,147,483,648.

Therefore, the result of int x = -2147483648; is that x is initialized with the value −2,147,483,648.

这篇关于评估`int x = -2147483648`会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆