7

I'm seeing strange errors when my C++ code has min() or max() calls. I'm using Visual C++ compilers.

Ashwin Nanjappa
  • 76,204
  • 83
  • 211
  • 292

6 Answers6

18

Check if your code is including the windows.h header file and either your code or other third-party headers have their own min()/max() definitions. If yes, then prepend your windows.h inclusion with a definition of NOMINMAX like this:

#define NOMINMAX
#include <windows.h>
Ashwin Nanjappa
  • 76,204
  • 83
  • 211
  • 292
2

Another possibility could be from side effects. Most min/max macros will include the parameters multiple times and may not do what you expect. Errors and warnings could also be generated.

max(a,i++) expands as ((a) > (i++) ? (a) : (i++))

afterwards i is either plus 1 or plus 2

The () in the expansion are to avoid problems if you call it with formulae. Try expanding max(a,b+c)
itj
  • 1,165
  • 1
  • 11
  • 16
2

Since Windows defines this as a function-style macro, the following workaround is available:

int i = std::min<int>(3,5);

This works because the macro min() is expanded only when min is followed by (, and not when it's followed by <.

MSalters
  • 173,980
  • 10
  • 155
  • 350
0

Ugh... scope it, dude: std::min(), std::max().

Pat Notz
  • 208,672
  • 30
  • 90
  • 92
0

I haven't used it in years but from memory boost assigns min and max too, possibly?

Orion Edwards
  • 121,657
  • 64
  • 239
  • 328
-1

Honestly, when it comes to min/max, I find it best to just define my own:

#define min(a,b) ((a) < (b) ? (a) : (b))
#define max(a,b) ((a) >= (b) ? (a) : (b))
dhorn
  • 687
  • 1
  • 5
  • 13
  • 4
    Which, frankly, is asking for trouble. In C++, use `using std::swap` and write your own swap when you can do better than the default. In C, at the very lease write `#define min(a,b) ((a) < (b) ? (a) : (b))` and MAKE SURE YOU DON'T CALL IT WITH ANYTHING WITH SIDE EFFECTS, because you will have multiple evaluation. – David Thornley Nov 24 '09 at 22:28