Why is std::min failing when windows.h is included?

The windows.h header file (or more correctly, windef.h that it includes in turn) has macros for min and max which are interfering.

You should #define NOMINMAX before including it.


In fact, you should probably do that even if there were no conflict, since the naive definition of the macro shows why function-like macros are a bad idea:

#define max(a,b) ((a)>(b)?(a):(b))

If you invoke that macro with, for example:

int x = 5, y = 10;
int c = max(x++, y--);

then y will not end up with what you expect. For example, it will expand to:

int c = ((x++)>(y--)?(x++):(y--));

That expression (unless undefined behaviour kicks in which would be even worse) will decrement y twice, not something you’re likely to expect.

I basically use macros only for conditional compilation nowadays, the other two major use cases of old (symbolic constants and function-like macros) are better handled with more modern language features (real enumerated types and inline function suggestion).

Leave a Comment