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?
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.
Related
The error message says:
In functionvoid LCSlength(std::__cxx11::string, std::__cxx11::string, int, int)
Error:
expression cannot be used as a function
lookup[ i ][ j ] = max (lookup[i - 1] [ j ],lookup[ i ] [ j - 1 ]);
#define max 20
int lookup[max][max];
void LCSlength(string x,string y,int m,int n)
{
for(int i = 1;i<=m;i++)
{
for(int j = 1;j<=n;j++)
{
if(x[i - 1] == y[j - 1])
lookup[i][j] = lookup[i - 1][j - 1] + 1;
else
lookup[i][j] = max(lookup[i - 1][j], lookup[i][j - 1]);
}
}
}
Use std::max(lookup[i - 1][j], lookup[i][j - 1]); and replace your macro name by something else, say maximum:
#define maximum 20
int lookup[maximum][maximum];
Solution
if you can use C++11 use
constexpr int max = 20;
or if you can't use C++11 use
const int max = 20;
And don't skip the namespace to avoid ambiguities:
lookup[i][j] = std::max(lookup[i - 1][j], lookup[i][j - 1]);
Explanation
You have a macro
#define max 20
Now the preprocessor is a quite stupid text-replacement tool, that will now replace every instance of "max" with "20". So you end up with
lookup[i][j] = 20(lookup[i - 1][j], lookup[i][j - 1]);
Which doesn't make any sense. Prime example why you shouldn't use macros in modern C++ ;)
You need to define the max function or use macro like this
#define MAX(a,b) ((a) > (b) ? (a) : (b))
refer to MIN and MAX in C
Edit
Preprocessors are case sensitive and it is advised to keep them in capital letters. Just for the sake of correct answer, I am putting them in small caps. You can use a function as well.
#define max(a,b) ((a) > (b) ? (a) : (b))
The problem is that you want to use the "max" function of stl, but you declared a variable called max at the beginning.
You should call std::max instead or change the name of your max variable.
In general, avoid using std to avoid those mistakes
I am working on a class assignment with starter code and included is this syntax that I've never seen before.
#define EVENT() (rand() % 2 > 0.5)
Can someone tell me what this does? Does it return something? I know the define is a macro that has a function called EVENT(), but what does the (rand() % 2 > 0.5) bit mean? If I use EVENT() in the code somewhere, do I treat it as a void function that just evaluates to that statement?
wherever EVENT() is used in the source code , the preprocessor substitutes EVENT() with rand() % 2 > 0.5 which will return a random 1 or 0, 1 if the rand() result was odd and 0 if the result was even.
Not sure how to word this but, Is there any way to increment a macro?
I have several offset macros, the first defined offset must be zero, the next one must be 1, and so on.
If I need to add an offset macro to the middle of the list, it can be cumbersome to increment all the offsets below it manually.
//How can I turn this...
// v This number needs to increment by 1 (no matter the order)
#define OFFSET_X 0
#define OFFSET_Y 1
#define OFFSET_Z 2
#define OFFSET_W 3
//Into something like this... (order of macros swapped yet the numbering still goes from 0 to 3)
int num = 0;
#define OFFSET_Z num++ // = 0 (was 2)
#define OFFSET_Y num++ // = 1 (was 1)
#define OFFSET_X num++ // = 2 (was 0)
#define OFFSET_W num++ // = 3 (was 3)
With the original order,
#define OFFSET_X 0
#define OFFSET_Y (OFFSET_X + 1)
#define OFFSET_Z (OFFSET_Y + 1)
#define OFFSET_W (OFFSET_Z + 1)
or with the revised order in the second part of your post,
#define OFFSET_Z 0
#define OFFSET_Y (OFFSET_Z + 1)
#define OFFSET_X (OFFSET_Y + 1)
#define OFFSET_W (OFFSET_X + 1)
etc. Since all this gets evaluated at compile time, anyway, there's no perf hit.
Or you could write a code generator, if you're really bored, and have it generate the values for you.
Or just use an enum. This is what they're for, and they're treated as constants by the compiler, anyway - but you get compile-time error checking which is far less effective with macros.
BUT, a better solution may be constexpr added in C++11.
In any case, if you only have four of these, this is overkill.
Just use an enum:
enum class offsets {
X = 0,
Y = 1,
Z = 2,
W = 3
};
and don't sweat it. Want auto-increments? Even easier:
enum class offsets { X = 0, y, z, w };
for the same effect.
Note I've suggested an enum class, so the usage is offsets::X, offsets::Y etc.
In some cases you may prefer an constexpr std::array, which you could then iterate over (something you can't do with macros or enums).
I have the following define macros:
#define NHID 5
#define NENT 10
#define NOUT 4
#define NWEIS (NENT + 1) * NHID + (NHID + 1) * NOUT
So everytime that the compiler finds a "NWEIS", it will replace "NEWIS" for "(NENT + 1) * NHID + (NHID + 1) * NOUT". But that is not what I want. I want it replace "NWEIS" by the actual value = 79, without having to declare extra variables in the memory. Is there a decent way to do this?
Macro replacement is mostly1 an iterative process.
What you will get, following macro substitution is an expression with the constants. And any decent compiler will be able to fold those constants (evaluate them at compile time) to give you the single value of 79.
For example, consider the program:
#define NHID 5
#define NENT 10
#define NOUT 4
#define NWEIS (NENT + 1) * NHID + (NHID + 1) * NOUT
int main (void) { return NWEIS; }
here's the pre-processor output from gcc -E:
int main (void) { return (10 + 1) * 5 + (5 + 1) * 4; }
and here's the relevant assembler code line it generates with gcc -S (the return value is placed into the eax register):
movl $79, %eax
Having said that, there are precious few reasons to use macros any more since you have constant "variables", inline suggestions to the compiler, enumerated types and so forth, all things that macros used to be very useful for.
I still find myself reaching for macros for quick'n'dirty code of course, but that's mostly because I'm an old codger, forged in the early C days before we even had prototypes :-)
It may be worthwhile rethinking your use of them as well, since you can replace it with something like:
const int nhid = 5;
const int nent = 10;
const int nout = 4;
const int nweis = (nent + 1) * nhid + (nhid + 1) * nout;
A smart compiler should still be able to optimise the calculations away at compile time and you'll most likely find that the variables are available in the debugger for you, something that often doesn't happen with macros.
1 Full details can be found in the C++11 standard, section 16.3 Macro replacement.
Suffice to say there are certain uses of # and ## within a macro that prevent further replacement of that token (the former replaces the token with a character string literal and the latter combines multiple tokens into a different token).
Since you're not using those, it's irrelevant here.
The macros you are using do not cost you extra memory. You have already acheived what you want.
Let's look at what a reasonable compiler will do.
Suppose you have this code.
#define NHID 5
#define NENT 10
#define NOUT 4
#define NWEIS (NENT + 1) * NHID + (NHID + 1) * NOUT
int f()
{
return NWEIS;
}
A reasonable compiler will obviously expand it into:
int f()
{
return (NENT + 1) * NHID + (NHID + 1) * NOUT;
}
The next step will than be:
int f()
{
return (10 + 1) * 5 + (5 + 1) * 4;
}
As this arithmetic expression consist of hard-coded numbers (constant expression) only, the compiler can treat the whole thing as a constant too.
int f()
{
return 79;
}
Note that this function is so small, a reasonable compiler will try its best to in-line the function.
However, it is much more preferable to do this:
constexpr int NHID = 5;
constexpr int NENT = 10;
constexpr int NOUT = 4;
constexpr int NWEIS = (NENT + 1) * NHID + (NHID + 1) * NOUT;
Just use
const int NHID = 5;
const int NENT 10;
const int NOUT 4;
const int NWEIS = (NENT + 1) * NHID + (NHID + 1) * NOUT;
A good optimizer will substitute these values at compile-time and not place any variables in memory, unless you do something such as take their address. Then you have the type safety and scoping of C++ without the macro evilness.
(Upper case names are by convention reserved for macros, so you may want to rename them slightly)
I came across a interview question which reads as follows:
"Write a simple C/C++ Macro to find maximum of two numbers without using std library or ternary operator".
I need your help in solving this. I know this is trivial but I couldn't find it. So, posting it here.
#include<iostream>
#define max(x,y) /*LOGIC HERE*/
using namespace std;
void main()
{
int a = 98453;
int b = 66394;
cout<<max(a,b);
}
Use Boolean operations to get 0 or 1 and then just add them up:
#define max(x,y) (((int)((x)<(y)) * (y)) + ((int)((y)<=(x)) * (x)))
#include <iostream>
#define max(x, y) [a = x, b = y](){ if (a<b) return b; else return a; }()
int main() {
using namespace std;
int a = 10;
int b = 20;
cout << max(10, 20);
cout << max(a, b);
};
a solution just for fun : >
compiled with c++14
would blow up if x, y has different types
#define max(x,y) (x+y + abs(x-y))/2 gives you what you are looking for. This works because abs(x-y) = max(x,y) - min(x,y). So, you can rewrite the expression as follows
(x + y) + abs(x-y) = max(x,y) + min(x,y) + max(x,y) - min(x,y)
= 2*max(x,y)
As pointed out in the comments, using abs might violate the conditions what you have asked for.
#define max(x, y) x - ((x-y) & ((x-y) >> 31))
This assumes x and y are 32 bit.
This works by the fact that the most-significant bit of a negative integer is 1.
Thus if x-y is negative (y is greater than x) then x - (x - y) = y.
If x-y is positive then x is greater than y, the most significant bit is zero and thus x - 0 = x.
The 31 represents the total # of bits of the variable - 1. (thus the most significant bit).
I imagine this is what they're looking for since it doesn't use comparisons.
Aww, so many nice solutions. I have another one exploiting that booleans convert to zero and one:
#define CONDITION(c, t, f) (c * t + (1 - c) * f)
#define MAX(a, b) CONDITION(a > b, a, b)
Nearby, I'm deliberately ALL_UPPERCASING this evil macro machinery. I'd say this is the actual point you should have raised in an interview.
Another crazy C++11-only approach, and cheating slightly with an extra struct declaration (could use a std::array if libraries were allowed) - for whatever it's worth (not much!)...
struct Max { int n_[2]; };
#define max(x,y) (Max{(x),(y)}.n_[(x) < (y)])