Perhaps inconsistent behavior

GCC 4.8.0 compilation in / for 32-bit.

I find the behavior of cases 2 and 6 to be confused:

int16_t s16 = 0;
double dbl = 0.0;

s16 = (int16_t)((double)32767.0); // 1: s16 = 32767
s16 = (int16_t)((double)32768.0); // 2: s16 = 32767
s16 = (int16_t)((double)-32768.0); // 3: s16 = -32768
s16 = (int16_t)((double)-32769.0); // 4: s16 = -32768

dbl = 32767.0;
s16 = (int16_t)dbl; // 5: s16 = 32767
dbl = 32768.0;
s16 = (int16_t)dbl; // 6: s16 = -32768  
dbl = -32768.0;
s16 = (int16_t)dbl; // 7: s16 = -32768
dbl = -32769.0;
s16 = (int16_t)dbl; // 8: s16 = -32768

I understand that the implementation is defined, but the sequence will still be enjoyable. Can someone explain what is happening?

+5
source share
2 answers

The behavior is not determined by the implementation, it is undefined, according to 6.3.1.4 (1):

If the value of the integer part cannot be represented as an integer type, the behavior is undefined. 61)

61) , , , . (−1, Utype_MAX+1).

C99, (50).

undefined , , , ,

1 << width_of_type

0, , 1, .

, , , undefined -, / / / .

+3

, "undefined" " ".

, , . , . , itrunc (double), boost:: math:: rounding_error, ( , , int16_t).

http://www.boost.org/doc/libs/1_53_0/libs/math/doc/sf_and_dist/html/math_toolkit/utils/rounding/trunc.html

, : , , , , , , , .

0

All Articles