Predict the output of following program.
#include <stdio.h>
#define MOBILE 0x01
#define LAPPY 0x02
int main()
{
unsigned char item=0x00;
item |=MOBILE;
item |=LAPPY;
printf("I have purchased ...:");
if(item & MOBILE){
printf("Mobile, ");
}
if(item & LAPPY){
printf("Lappy");
}
return 1;
}
Answer: B
Correct answer: I have purchased ...:Mobile, Lappy
This is the flags idiom in full. MOBILE is 0x01 and LAPPY is 0x02 - different bit positions, which is what makes them independently storable in one byte.
The two |= operations set both bits, leaving item at 0x03. Each if then tests one bit with AND, and both tests are non-zero, so both strings print. Note that if uses each test as a truth value, so the results 0x01 and 0x02 both count as true despite being different numbers.
Please log in or register to report this question.