I'm trying to do something similar to this:
#include <iostream>
int main()
{
std::cout << 1 << 5 << std::endl;
}
You're right. You are trying to do something similar to that. However, the problem has nothing to do with the macro (I mean, that's a problem too, but more on that later). The problem is your goal isn't what you mean. You don't mean std::cout << 1 << 5 << std::endl;
, you mean std::cout << (1 << 5) << std::endl;
The difference is that the first breaks down into something like this:
std::cout << 1;
std::cout << 5;
std::cout << std::endl;
While what you want is something like this:
int i = 1 << 5;
std::cout << i;
std::cout << std::endl;
Or something to that effect.
The answer is simple: either use parenthesis in your cout
statement, or put it in your macro (the better option):
// either
cout << (BIT_SHIFT(1, 5)) << std::endl;
// or
#define BIT_SHIFT(x,y) (x << y)
...
cout << BIT_SHIFT(1, 5) << std::endl;
Also, as someone else suggested, you can even go a step further if you like and do this:
#define BIT_SHIFT(x,y) ((x) << (y))
...
cout << BIT_SHIFT(1, 5) << std::endl;
That way, if you do something weird in x
or y
, your code doesn't break.