Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinity in MSVC++

I'm using MSVC++, and I want to use the special value INFINITY in my code.

What's the byte pattern or constant to use in MSVC++ for infinity?

Why does 1.0f/0.0f appear to have the value 0?

#include <stdio.h>
#include <limits.h>

int main()
{
  float zero = 0.0f ;
  float inf = 1.0f/zero ;

  printf( "%f\n", inf ) ; // 1.#INF00
  printf( "%x\n", inf ) ; // why is this 0?

  printf( "%f\n", zero ) ; // 0.000000
  printf( "%x\n", zero ) ; // 0

}
like image 916
bobobobo Avatar asked Mar 29 '10 13:03

bobobobo


2 Answers

Use numeric_limits:

#include <limits>

float maxFloat = std::numeric_limits<float>::infinity();
like image 161
GManNickG Avatar answered Oct 12 '22 01:10

GManNickG


printf("%x\n", inf) expects an integer (32 bit on MSVC), but receives a double. Hilarity will ensue. Err, I mean: undefined behavior.

(And yes, it receives a double since for a variable argument list, floats are promoted to double).

Edit anyways, you should use numeric_limits, as the other reply says, too.

like image 43
peterchen Avatar answered Oct 12 '22 02:10

peterchen