Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange C++ errors with code that has min()/max() calls

Tags:

c++

c

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

like image 612
Ashwin Nanjappa Avatar asked Aug 18 '08 04:08

Ashwin Nanjappa


3 Answers

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>
like image 168
Ashwin Nanjappa Avatar answered Oct 29 '22 10:10

Ashwin Nanjappa


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)
like image 39
itj Avatar answered Oct 29 '22 11:10

itj


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 <.

like image 33
MSalters Avatar answered Oct 29 '22 11:10

MSalters