A book on C programming states,
enum corvid { magpie , raven , jay , chough , corvid_num , };
# define FLOCK_MAGPIE 1 U
# define FLOCK_RAVEN 2 U
# define FLOCK_JAY 4 U
# define FLOCK_CHOUGH 8 U
# define FLOCK_EMPTY 0 U
# define FLOCK_FULL 15 U
int main ( void ) {
unsigned flock = FLOCK_EMPTY ;
if ( something ) flock |= FLOCK_JAY ;
...
if ( flock & FLOCK_CHOUGH )
do_something_chough_specific ( flock ) ;
Here the constants for each type of corvid are a power of two, and so they have exactly one bit set in their binary representation. Membership in a flock can then be handled through the operators: |= adds a corvid to flock, and & with one of the constants tests whether a particular corvid is present
Question. "if ( something ) flock |= FLOCK_JAY ; " adds a corvid to flock but why not use assignment operator for that or "flock = FLOCK_JAY".
Also, is "if ( flock & FLOCK_CHOUGH )" gonna yield a bool type value?
CodePudding user response:
Question. "if ( something ) flock |= FLOCK_JAY ; " adds a corvid to flock but why not use assignment operator for that or "flock = FLOCK_JAY".
|=
is used whenever one wants to preserve the other bits already set inside the variable. In this specific case it doesn't matter if =
or |=
is set since flock
has the value zero.
Also, is "if ( flock & FLOCK_CHOUGH )" gonna yield a bool type value?
It will yield an unsigned int
since both operands are of that type. It will hold a value which is either zero or non-zero. This can be regarded as equivalent to a boolean condition though. It will only get bool type if you explicitly do bool b = flock & FLOCK_CHOUGH;
.
CodePudding user response:
Q1: Assigning instead of ORing would knock out other bird types. Say
flock = FLOCK_MAGPIE;
If you set
flock = FLOCK_JAY;
there would be no magipies in the flock but if you
flock |= FLOCK_JAY;
the flock would contain both jays and magpies.
Q2: The condition in the if statement doesn't yield a bool. Any non-zero value is true. A zero value is false. If you want a boolean value, try
if ((flock & FLOCK_CHOUGH) != 0)