bobobobo
bobobobo

Reputation: 67224

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

}

Upvotes: 8

Views: 7876

Answers (5)

GManNickG
GManNickG

Reputation: 503855

Use numeric_limits:

#include <limits>

float maxFloat = std::numeric_limits<float>::infinity();

Upvotes: 20

dan04
dan04

Reputation: 90995

In the variable arguments list to printf, floats get promoted to doubles. The little-endian byte representation of infinity as a double is 00 00 00 00 00 00 F0 7F.

As peterchen mentioned, "%x" expects an int, not a double. So printf looks at only the first sizeof(int) bytes of the argument. No version of MSVC++ defines int to be larger than 4 bytes, so you get all zeros.

Upvotes: 3

peterchen
peterchen

Reputation: 41096

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.

Upvotes: 11

Hans Passant
Hans Passant

Reputation: 941455

That's what happens when you lie to printf(), it gets it wrong. When you use the %x format specifier, it expects an integer to be passed on the stack, not a float passed on the FPU stack. Fix:

printf( "%x\n", *(__int32*)&inf ) ;

You can get infinity out of the <limits> C++ header file:

float inf = std::numeric_limits<float>::infinity().

Upvotes: 2

fretje
fretje

Reputation: 8372

Take a look at numeric_limits::infinity.

Upvotes: 2

Related Questions