-
understand masking bits
Hi there,
I am not quite understanding why the program described at Question11-1 from (Page 169) is working - I am expecting it not to work. Might somebody please explain why.
The result should 0 after masking after masking the bits in the line 'if ((flags & DIRECT_CONNECT) != 0)', right?
--- output of program ---
% ./question11-1
High speed set
Direct connect set
%
---- snip -----
Code:
#include <iostream>
const int HIGH_SPEED = (1<<7); /* modem is running fast */
// we are using a hardwired connection
const int DIRECT_CONNECT = (1<<8);
char flags = 0;
int main()
{
flags |= HIGH_SPEED; // we are running fast
flags |= DIRECT_CONNECT; // because we are wired together
if ((flags & HIGH_SPEED) != 0)
std::cout << "High speed set\n";
if ((flags & DIRECT_CONNECT) != 0)
std::cout << "Direct connect set\n";
return (0);
}
-
Why? The code turns on the DIRECT_CONNECT bit with the line: flags |= DIRECT_CONNECT; so it will return non-zero when you check for that bit later.
-
Your bitwise & in the conditional doesn't modify the flags set in any way. The expression returns a temporary boolean variable that's evaluated (as true in this case) and then disappears. Since flags is never changed, it SHOULD report exactly what you see as the output.