c++ - Weird integer overflow logic -
for following code overflow sadly cannot seem understand why.
std::int8_t smallvalue = -1; unsigned int value = 500; std::uint8_t anothersmallvalue = 1; auto test = smallvalue * value * anothersmallvalue;
afterwards test
quite large value.
could explain, happens here?
when compiler sees smallvalue * value
, must decide data type of result going be, given input data types signed
(8 bits) , unsigned int
(usually, either 16 or 32 bits). rules of c++ state in situation, result unsigned. therefore, value of smallvalue * value
cannot -500
, expecting; instead, value -500
interpreted positive number.
furthermore, here multiplying 8-bit value value typically either 16- or 32-bit. rules of c++ in scenario state smaller-storage value first cast same size larger; in case result of smallvalue * value
indeed large enough store number of magnitude 500
.
proceeding multiply unsigned quantity anothersmallvalue
(=1) results in unsigned
same value.
because using auto
, return type therefore deduced unsigned
.
simply casting signed
(by, example, defining value test
int
, rather auto
, in turn typically cast result of entire operation signed
value, without changing bits internally; display -500
, expect; however, other posters have noted, rather dangerous in theory because it's not techincally guaranteed work, although work way today's compilers.
Comments
Post a Comment