Reputation: 3164
I have this example from C++ primer 5th edition. ch-19 Bit fields:
typedef unsigned int Bit;
class File {
Bit mode: 2; // mode has 2 bits
Bit modified: 1; // modified has 1 bit
Bit prot_owner: 3; // prot_owner has 3 bits
Bit prot_group: 3; // prot_group has 3 bits
Bit prot_world: 3; // prot_world has 3 bits
// operations and data members of File
public:
// file modes specified as octal literals; see § 2.1.3 (p. 38)
enum modes { READ = 01, WRITE = 02, EXECUTE = 03 };
File &open(modes);
void close();
void write();
bool isRead() const;
void setWrite();C++ Primer, Fifth Edition
};
File &File::open(File::modes m)
{
mode |= READ; // set the READ bit by default
// other processing
if (m & WRITE) // if opening READ and WRITE
// processing to open the file in read/write mode
return *this;
}
What makes me wonder is: the mode
member is just 2 bits
, so it can hold values: 0, 1, 2, 3
( 00 01 10 11
in binary). The value 3
is defined as an enumeration that specifies the opening mode as execute
, but if it is opened here for execute then it is opened too for writing: 3 & 2 = 2
3 & 1 = 1
, which I think is a mistake. Normally each mode is independent from any other mode.
I mean, for example, in the member function open()
, mode |= READ
is OK to set the read bit, which is the first one. Now if(m & WRITE)
looks meaningless if the user already has opened the file for Executing 3
(11
in binary).
What do you think?
Upvotes: 1
Views: 83
Reputation: 596041
The mode
field is not being treated as a bitmask, and the modes
type is not defining values in powers of 2. So you should not be using bitwise operations to set/query the mode
, for exactly this reason that EXECUTE
shares bits with READ
and WRITE
, which goes against your desire to have each mode be independent. In a proper bitmask, EXECUTE
would be defined as 4
(100
in binary), not 3
.
Upvotes: 4