Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

int - C assigning values greater than data type ranges

In C int type can having following +ve range of values 2,147,483,647

source:https://msdn.microsoft.com/en-IN/library/s3f49ktz.aspx

I would like to know what happens if I assign values greater than int can hold, how the values are truncated or what is exactly stored, if I do this

int var=2147483648;

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
int var = 2147483648;

The actual behavior for signed integers is implementation-defined. Most possibly the value will be narrowed (in other words "cut-of") to four least significant bytes (assuming that sizeof(int) = 4).

The constant 2147483648 is likely of type long (or long long if former is not enough to hold it), so what is actually happening here is like:

int var = (int) 2147483648LL;

The actual value after conversion is -2147483648 as only sign bit is set (assuming two's complement representation).

Citing from C11 (N1570) §6.3.1.3/p3 Signed and unsigned integers (emphasis mine):

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

For instance, with GCC, the result is to reduce result modulo 2^N, which is effectively the same as bytes "cut off":

For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type; no signal is raised.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...