Reputation: 493
I'm having a problem with std::max
. I can't figure it out.
int border = 35;
int myInt = 2;
int myOtherInt = 3;
int z = std::max(myInt + 2 * border, myOtherInt + 2 * border);
I've included the algorithm standard header. When I mouse over max, I am getting:
Error: expected an identifier
And a compile errors of:
error C2589:
'('
: illegal token on right side of'::'
error C2059: syntax error :'::'
What is wrong?
Upvotes: 49
Views: 43651
Reputation: 3908
Just a brief collection of other answers.
If max(a,b)
is already #define
d, (by including windows.h or some Windows-related project, etc.)
#define NOMINMAX
#undef max
(std::max)
- Use parentheses to prevent function-like macro1)std::max<int>
- Explicitly give a type for the template.Precaution: If some part of the project depends on the min/max macro, e.g. using MFC, then just simply doing #define NOMINMAX
can cause some problem.
Maybe #undef NOMINMAX
should be needed, e.g.:
// just an example
#define NOMINMAX
#include <windows.h>
#undef NOMINMAX
// ...
(For more info, please take a look at the answers of this question.)
1) Function-like macros only expand when the next thing after is an opening parenthesis. When surrounding the name with parentheses, the next thing after the name is a closing parenthesis, so no expansion occurs. [ref]
Upvotes: 2
Reputation: 62975
Hazarding a guess, since you're using VC++ – put this before any #include
s:
#define NOMINMAX
windows.h
defines macros named min
and max
like so:
#define min(a,b) (((a) < (b)) ? (a) : (b))
#define max(a,b) (((a) > (b)) ? (a) : (b))
The Windows SDK has contained these macros since before C++ was standardized, but because they obviously play havoc with the C++ standard library, one can define the NOMINMAX
macro to prevent them from being defined.
As a rule, if you're using C++ (as opposed to C) and including windows.h
, always define NOMINMAX
first.
Upvotes: 93
Reputation: 29
The "using" declaration (see using Declaration) is yet another way to work around the issue:
int border = 35;
int myInt = 2;
int myOtherInt = 3;
using std::max;
int z = max(myInt + 2 * border, myOtherInt + 2 * border);
It allows using std::max without explicit qualification.
Upvotes: 2
Reputation: 21058
If you're on VC++, you can either use #define NOMINMAX
prior to including any headers, or do (std::max)(myInt + 2 * border, myOtherInt + 2 * border)
Upvotes: 24
Reputation: 32240
Have you tried using ::std::max
instead? If this doesn't work, something is messing with your std namespace.
Upvotes: 0
Reputation: 20726
I would say that either max
is #define
's to something else or you need to explicitly invoke the template via std::max<int>
.
Upvotes: 4