Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is casting of infinity to integer undefined?

Is the casting of infinity (represented by float) to an integer an undefined behavior?

The standard says:

4.10 Floating-integral conversions

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.

but I can't tell whether "truncated value cannot be represented" covers infinity.

I'm trying to understand why std::numeric_limits<int>::infinity() and static_cast<int>(std::numeric_limits<float>::infinity() ) have different results.

#include <iostream> #include <limits>  int main () {     std::cout << std::numeric_limits<int>::infinity () << std::endl;     std::cout << static_cast<int> (std::numeric_limits<float>::infinity () ) << std::endl;     return 0; } 

Output:

0   -2147483648   

The result of std::numeric_limits<int>::infinity() is well defined and equal to 0, but I can't find any information about casting infinity.

like image 272
Gluttton Avatar asked Aug 05 '16 18:08

Gluttton


People also ask

How do you convert int to infinity?

Setting an int Infinity: Integers are inherently finite; that is why we cannot define them to a right infinity. The nearby value that we can get is by initializing an “int” to its extreme value. The closest we can get by setting a variable to the maximum value that is double “a = std: numeric_limits<int>:: max();”.

What does casting to an int do?

Casting to an int will truncate toward zero. floor() will truncate toward negative infinite. This will give you different values if bar were negative.

How do you know if a float is infinity?

To check if a Float is isInfinite, use the isInfinite() method and to check for NAN, use the isNaN() method.


1 Answers

Casting of infinity to integer is undefined.

The behavior is undefined if the truncated value cannot be represented in the destination type.

Says it all. Since truncation removes precision but not magnitude, a truncated infinity is still infinity and integers cannot represent infinity.

like image 156
nate Avatar answered Sep 22 '22 19:09

nate