2
1: #include <windows.h>

2: int& max(int& a, int& b)
3: {
4:   return a > b ? a : b;
5: }

6: int main()
7: {
8:   return 0;
9: }

Visual Studio 2008 Express Edition shouts:

1>e:...\main.cpp(2) : error C2062: type 'int' unexpected

1>e:...\main.cpp(2) : error C2062: type 'int' unexpected

1>e:...\main.cpp(2) : error C2059: syntax error : ')'

1>e:...\main.cpp(3) : error C2143: syntax error : missing ';' before '{'

1>e:...\main.cpp(3) : error C2447: '{' : missing function header (old-style formal list?)

It seems to work if I replace windows.h with stdio.h or iostream (or if I remove it)

Why is this?

3
  • I'm guessing your windows.h is corrupted somehow. Did you happen to open it up in a text editor to look what's in it at some point? You might have mistakenly edited it. Commented Apr 21, 2013 at 16:15
  • 6
    windows.h has min and max macros. Commented Apr 21, 2013 at 16:16
  • 1
    Be very careful when returning references here – in 99% of the case this is not what you want (for instance with your code this wouldn’t work: max(4, 5)). Don’t be afraid to return by value, it’s efficient and will avoid making unnecessary copies. Commented Apr 21, 2013 at 16:23

1 Answer 1

5
#include <windows.h>

#undef min
#undef max

int & max(int& a, int& b)
{
    return a > b ? a : b;
}
int main()
{
    return 0;
}

<windows.h> defines macros for max and min which interfere with yours.

Other ways

  • Rename your functions.

  • use NOMINMAX. This is the common solution recommended for using some STL headers which define min and max themselves.

    #define NOMINMAX
    #include <windows.h>
    
Sign up to request clarification or add additional context in comments.

3 Comments

There is another (imho preferable) way: just define NOMINMAX before including windows.h (or use a compiler flag to add the definition). This will stop windows.h from defining both macros.
@ollb No. Apparently that fails under some circumstances (although I suspect that those circumstances are that it was forgotten somehow; defining it via the compiler options should be safe).
Well I personally never had a problem with NOMINMAX and I think it should be mentioned here. Also @user93353 as far as I know WINDOWS_LEAN_AND_MEAN won't include the effect of NOMINMAX.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.