'C' Reason the output

India
January 28, 2007 9:29am CST
Hi Friends Can any body tell me the output for the following C program and Reason it void main() { int a=10; (a&8==8:printf("Bit 3 is on"):printf(Bit 3 is off")); }
2 responses
@dholey (1383)
• India
29 Jan 07
let me try...... the first thing i want to mention is YOU HAVE NOT USED ? as your program seems to work on it so the code must be ... (a&8==8 ? printf("on"):printf("off")); (by some typing mistake you have mentioned : instead of ? after 8==8 ) you are using the bitwise and operator which compares bits and if both the comparing bits are on then it returns the comapring bits on but its priority is less the == operators so 8==8 will be performed first and it will be evaluated as true so it becomes 1 then the 10 is bitwise anded with 1 and the comparison will be as follows 1010 binary represantation of 10 & 0001 binary representation of 1 ________ 0000 the result is 0 (FALSE) AND THATS WHY THE FALSE AREA OF TERNARY OPERATOR IS EXECUTED WHICH SHOWS Bit 3 is off if you increase the priority of bitwise comparison using () like (a&8)==8 then you will get Bit 3 is on , because in this case the bitwise comparison will be performed first (before comparing 8==8 ) ........
@dholey (1383)
• India
31 Jan 07
i have specified in details ... if you needed it again i will elaborate it again see in the condition you have mentioned (a&8==8) the priority of & is less then == operator so the equation will be (a & (8==8)) so 8==8 is evaluated first which yields true i.e. 1 so new equation will be (a&1) now the bit-sets of a and 1 is compared (10 in binary is 1010 and 1 is 0001) when anded this bit-sets the result will be 0 which stands for false so the false block is executed and you get "3 bit is off "
• India
31 Jan 07
Nice dholey
@raghwagh (1527)
• India
28 Jan 07
This program will give many compilation errors.The correct code will be as follows, void main() { int a=10; ((a&8)==8)?printf("Bit 3 is on"):printf("Bit 3 is off"); } This should be the correct code.I think this will compile and give result as Bit 3 is off What do you say on it.
• India
28 Jan 07
The code which i gave you is correct Raghwagh. But you answered correctly. Can you reason it?