Iurii Selinnyi
Iurii Selinnyi

Reputation: 524

min and max simply doesn't work in this case?

So here's the code which works. Posted it without any changes. There is X and Y values which must be betwen 0 and 1024. tyleSize is 1024;

//for X

int loffx=accurate(curphisobj->x) + (rand() % 100) - 50; //some math, doent matter
loffx=max(loffx,1);
loffx=min(loffx,tyleSize);

//for Y

int loffy=accurate(curphisobj->y) + (rand() % 100) - 50;
loffy=max(loffy,1);
loffy=min(loffy,tyleSize-3);

But if I write it like this:

int loffy=min(max(accurate(curphisobj->y) + (rand() % 100) - 50,1),tyleSize - 2);
int loffx=min(max(accurate(curphisobj->x) + (rand() % 100) - 50,0),tyleSize);

I get loffx and loffy 1034, 1029, -5, - 2, all kinds of nombers uncut by max and min.

Is there something i dont know about C++ compiler, or there's some dumb mistake?

Upvotes: 1

Views: 473

Answers (1)

Derek Ledbetter
Derek Ledbetter

Reputation: 4895

Make sure that you're actually using the min and max functions from <algorithm>, and not some macros defined elsewhere. For instance, the Windows header windef.h defines max like this:

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

This won't work in your code because it potentially evaluates each argument twice, and rand by design returns a different result each time.

Try viewing the source after preprocessing to see if you're using the macros. You can turn off the Windows macros by defining NOMINMAX before including any headers.

Upvotes: 9

Related Questions