recently i understood at last how can i store more values in an int with bytwise operators,
also, i have read that #define directives are evil for a number of reasons.
one of them:
#define SEVEN 2 + 5
int result = SEVEN * 5;
cout << result; // you would expect that the console prints 35, but it doesn't
/*
let's take a look why this happens:
the folowing line: int result = SEVEN * 5;
it is converted by the compiler to this:
int result = 2 + 5 * 5; // this will printout 27, not 35 as expected
so, if you'd want a correct answer, you'd have to put 2 + 5 into brackets at the define redirective like this: #define SEVEN (2 + 5)
*/
usually, bytwise operators are used to store different values into one single variable
here is an example where we use an int to denote some flags:
// random flags, the meanning does not matter
#define FLAG_FAST 1 << 0
#define FLAG_VISIBILE 1 << 1
#define FLAG_BIG 1 << 2
// ... etc
// function to set some flags to an integer
void SetFlags( int &flags )
{
if( ... )
flags |= FLAG_FAST;
if( ... )
flags |= FLAG_BIG;
if( ... )
flags |= FLAG_VISIBLE;
}
int flags = 0;
SetFlags( flags );
// now we want to use our flags
if( flags & FLAG_BIG )
{
// do stuff
}
// ... etc
what i want to ask is
when we check for some flags like in this line: if( flags & FLAG_BIG ),
the compiler transforms that code into this: if( flags & 1 << 2 )
heh, would be this calculeted as if( (flags & 1) << 2 ), or as if( flags & (1 << 2) )
i've noticed that the compiler treats it as if( flags & (1 << 2) ) and i don't understand why. does the '<<' and '>>' operators have a bigger precedence than '&' operator?