Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
957 views
in Technique[技术] by (71.8m points)

c - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...