c - Can a int16_t to int conversation result in implementation-defined behavior? -


in section 7.18.1.1 paragraph 1 of c99 standard:

the typedef name intn_t designates signed integer type width n, no padding bits, , two’s complement representation.

according c99 standard, exact-width signed integer types required have two's complement representation. means, example, int8_t has minimum value of -128 opposed one's complement minimum value of -127.

section 6.2.6.2 paragraph 2 allows implementation decide whether interpret sign bit sign , magnitude, two's complement, or one's complement:

if sign bit one, value shall modified in 1 of following ways:
— corresponding value sign bit 0 negated (sign , magnitude);
— sign bit has value -(2n) (two’s complement);
— sign bit has value -(2n - 1) (ones’ complement).

the distinct between methods important because minimum value of integer in two's complement (-128) can outside range of values representable in ones' complement (-127 127).

suppose implementation defines int types having ones' complement representation, while int16_t type has two's complement representation guaranteed c99 standard.

int16_t foo = -32768; int bar = foo; 

in case, conversion int16_t int cause implementation-defined behavior since value held foo outside range of values representable bar?

yes.

specifically, conversion yield implementation-defined result. (for value other -32768, result , behavior defined.) or conversion raise implementation-defined signal, don't know of implementations that.

reference conversion rules: n1570 6.3.1.3p3:

otherwise, new type signed , value cannot represented in it; either result implementation-defined or implementation-defined signal raised.

this can happen if:

  • int 16-bits (more precisely, has 15 value bits, 1 sign bit, , 0 or more padding bits)
  • int uses one's-complement or sign-and magnitude
  • the implementation supports two's-complement (otherwise won't define int16_t).

i'd surprised see implementation meets these criteria. have support both two's-complement , either one's complement or sign-and-magnitude, , have chose 1 of latter type int. (perhaps non-two's-complement implementation might support two's-complement in software, sake of being able define int16_t.)

if you're concerned possibility, might consider adding 1 of header files:

#include <limits.h> #include <stdint.h>  #if !defined(int16_min) #error "int16_t not defined" #elif int_min > int16_min #error "sorry, can't cope weird implementation" #endif 

the #errors not trigger on sane real-world implementation.


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -