C assigning values greater than data type ranges

2019-09-22 02:22发布

问题:

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;

回答1:

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.



回答2:

As you cited the linked statement, it is wrong. However, the linked page states correctly that it is valid for that specific implementation. Read the standard for minimum ranges of the standard types.

Actual sizes are in limits.h. You should not rely on anything else. If you need a specific size, use stdint.h types.

If you assign a signed value to an object which cannot hold that value, the result is implementation defined. A proper compilers allows to enable warnings for such issues - use them!

OTOH, for an unsigned value, it is very well defined (same section of the standard). Simply put, the upper bits are just ignored.



回答3:

Typically if the type is initialised in the source code, as in your example, you could get a compiler warning or error. Compile with highest warning levels possible.

If the overflow is the result of a calculation, it would be undefined. In practice this results in a wrap around or truncation, possibly with an overflow error.



回答4:

In C, there is no checking for overflow. The result is implementation defined.



标签: c int range