12

In Xcode, this compiles fine:

float falloff = fmin(1.0, fmax(0.0, distanceSqrd/cRadius));

However in Visual Studio 2010 it errors, and I have to use max instead of fmax. distanceSqrd and cRadius are also both floats.

It's the only part of my code that doesn't seamlessly cross compile...

Any ideas why?

Undo
  • 25,519
  • 37
  • 106
  • 129
  • possible duplicate of [Use of min and max functions in C++](http://stackoverflow.com/questions/1632145/use-of-min-and-max-functions-in-c) – stijn May 16 '13 at 10:08
  • I am sure your program was a bit longer than that (`#include` ?) – Marc Glisse May 16 '13 at 10:10
  • Well, one originates in C99, the other in C++98 ... – PlasmaHH May 16 '13 at 10:14
  • What is the actual error VS brings? By the way, while *"`distanceSqrd` and `cRadius` are also both floats"*, `1.0` and `0.0` certainly aren't. I hope you `#include`d either `` or, much more preferably, `` (in which case you should also qualify your calls if you don't have a `using` somewhere. while in VS this shouldn't be neccessary, it is not guaranteed that those functions are available in global namespace when using the proper C++ header ``). – Christian Rau May 16 '13 at 10:42
  • 1
    Oh wait, those are actually from `C++11`'s extensions to ``, which VS doesn't support yet. Answer found. – Christian Rau May 16 '13 at 10:47

1 Answers1

22

The functions std::fmax and std::fmin from the <cmath> header (or fmax and fmin from <math.h>) are a C++11 feature and along with many other new mathematical functions one that Visual Studio 2010 doesn't support yet (neither does 2012). So for portability it is advisable to replace them by std::min and std::max from <algorithm>.

The actual difference is, that fmin and fmax are mathematical functions working on floating point numbers and originating from C99 (and might be implemented intrisically by actual specialized CPU instructions where possible), while min and max are general algorithms usable on any type supporting < (and are probably just a simple (b<a) ? b : a instead of a floating point instruction, though an implementation could even do that with a specialization of min and max, but I doubt this).

They also behave slightly different for special floating point arguments. While it is not entirely specified how min and max will respond to NaNs, I think (though from the above definition they should always return the 1st operand), fmin and fmax are clearly specified to always return the other (non-NaN) argument when one is NaN, if the implementation is IEEE 754 conformant (which any modern PC implementation usually is).

Christian Rau
  • 45,360
  • 10
  • 108
  • 185