views:

631

answers:

5

What’s the best, platform-independent way to obtain the maximum value that can be stored in a float in C++?

+22  A: 

std::numeric_limits

Georg Fritzsche
A: 
#include <float.h>

then use FLT_MAX

tster
standard library headers are best imported without the extension. See this SO question http://stackoverflow.com/questions/441568/when-can-you-omit-the-file-extension-in-an-include-directive for an overview.
Francesco
+3  A: 
#include <cfloat>

Then use the macro FLT_MAX

Ref: cfloat / float.h

Clifford
Actually in C++, prefer gf's suggestion.
Clifford
Including <cfloat> defines a whole boatload of macros, which (among other things) don't respect scope, so including <limits> and using numeric_limits<float> is cleaner.Since he specifically mentioned platform independence, I'll also mention that IF you're doing to use FLT_MAX anyway, it's a bit more portable to include <float.h> instead of <cfloat>. A conforming C++ compiler will have the latter, but some older ones won't (but will still have float.h, which dates back to the C89/90 standard).
Jerry Coffin
@Jerry: All good points, and in fact I already conceded that in my earlier comment.
Clifford
+16  A: 

std::numeric_limits<float>::max()

hrnt
+7  A: 

std::numeric_limits

// numeric_limits example
#include <iostream>
#include <limits>
using namespace std;

int main () {

  cout << "Minimum value for float: " << numeric_limits<float>::min() << endl;
  cout << "Maximum value for float: " << numeric_limits<float>::max() << endl;
  cout << "Minimum value for double: " << numeric_limits<double>::min() << endl;
  cout << "Maximum value for double: " << numeric_limits<double>::max() << endl;
  return 0;
}
Todd
It should be noted that the calls to min() for floating-point types return the minimum positive value, not the minimum value. There's a big difference.
James McNellis