Search code examples
c++visual-studio-2005

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


#include <algorithm>
#include <Windows.h>

int main()
{
    int k = std::min(3, 4);
    return 0;
}

What is windows doing if I include Windows.h? I can't use std::min in visual studio 2005. The error message is:

error C2589: '(' : illegal token on right side of '::'
error C2059: syntax error : '::'

Solution

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