Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the result of casting float +INF, -INF, and NAN to integer in C?

Tags:

c

math

standards

Does any standard specifies what should be the output?

For example this code:

#include <stdio.h>
#include <math.h>

int main(int argc, char** argv) {
  float a = INFINITY;
  float b = -INFINITY;
  float c = NAN;

  printf("float %f %f %f\n", a, b, c); 
  printf("int %d %d %d\n", (int) a, (int) b, (int) c); 
  printf("uint %u %u %u\n", (unsigned int) a, (unsigned int) b, (unsigned int) c); 
  printf("lint %ld %ld %ld\n", (long int) a, (long int) b, (long int) b); 
  printf("luint %lu %lu %lu\n", (unsigned long int) a, (unsigned long int) b, (unsigned long int) c); 

  return 0;
}

Compiled on gcc version 4.2.1 (Apple Inc. build 5664) Target: i686-apple-darwin10

Outputs:

$ gcc test.c && ./a.out 
float inf -inf nan
int -2147483648 -2147483648 -2147483648
uint 0 0 0
lint -9223372036854775808 -9223372036854775808 -9223372036854775808
luint 0 9223372036854775808 9223372036854775808

Which is quite weird. (int)+inf < 0 !?!

like image 560
Przemyslaw Zych Avatar asked Oct 21 '10 11:10

Przemyslaw Zych


People also ask

What is NaN and inf in C?

In comparison operations, positive infinity is larger than all values except itself and NaN, and negative infinity is smaller than all values except itself and NaN. NaN is unordered: it is not equal to, greater than, or less than anything, including itself.

What is NaN value in C?

NaN, an acronym for Not a Number is an exception that usually occurs in the cases when an expression results in a number that is undefined or can't be represented. It is used for floating-point operations. For example: The square root of negative numbers.

Is NaN infinite?

In floating-point calculations, NaN is not the same as infinity, although both are typically handled as special cases in floating-point representations of real numbers as well as in floating-point operations.

How to check if argument is NaN in C?

Master C and Embedded C Programming- Learn as you go To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.


1 Answers

As Paul said, it's undefined:

From §6.3.1.4:

6.3.1.4 Real floating and integer

When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.50)

Infinity isn't finite, and the integral part can't be represented in an integral type, so it's undefined.

like image 115
Matthew Flaschen Avatar answered Oct 22 '22 17:10

Matthew Flaschen