Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast from double to size_t yields wrong result?

The following code works. My question is, should 2) not lead to a result very close to 1) ? Why is 2) casted to such a small amount ? Whereby, maybe worth to note 2) is exactly half of 1):

std::cout << "1)  " << std::pow(2, 8 * sizeof(size_t)) << std::endl;
std::cout << "2)  " << static_cast<size_t>(std::pow(2, 8 * sizeof(size_t))) << std::endl; 

The output is:

  1. 18446744073709551616
  2. 9223372036854775808
like image 773
ByronB Avatar asked Dec 18 '22 12:12

ByronB


1 Answers

It is due to that part of the specification:

7.3.10 Floating-integral conversions [conv.fpint]

A prvalue of a floating-point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.

The value 18446744073709551616 (that's the truncated part) is larger than std::numberic_limit<size_t>::max() on your system, and due to that, the behavior of that cast is undefined.

like image 74
t.niese Avatar answered Jan 03 '23 08:01

t.niese