简体   繁体   中英

What happens when evaluating `int x = -2147483648`?

What happens when evaluating

int x = -2147483648

?

  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.

  2. 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?

Thanks.

Your analysis in this question is right. Because the value is in the range of int and is converted to int as part of the initialization (note: the same would happen for assignment), everything works as intended.

As for the hidden part of your question you didn't ask, since it keeps getting closed as a duplicate, this does not mean you can define INT_MIN as -2147483648 . The magic is in the = (as assignment operator or a token in the initialization construct). In contexts where it's not being used, there are all sorts of ways that -2147483648 having type long or long long rather than int breaks semantic requirements on INT_MIN . For example:

  • (INT_MIN < 0U) == 0 (because both operands are promoted to unsigned ), but
  • (-2147483648 < 0U) == 1 (because both operands are promoted to long or long long ).

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

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 .

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 .

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM