Discussion
What will be the output of the following C code?
#include <stdio.h>
int main()
{
if (7 & 8)
printf("Honesty");
if ((~7 & 0x000f) == 8)
printf("is the best policy\n");
}
Answer: C
Correct answer: is the best policy
Take the two tests separately. \( 7 = 0111_2 \) and \( 8 = 1000_2 \) have no bits in common, so 7 & 8 is 0 and the first printf does not run.
For the second, ~7 inverts every bit, giving ...11111000. Masking with 0x000f keeps only the low four bits, leaving \( 1000_2 = 8 \), so the test is true and is the best policy is printed alone. The mask is what makes the result independent of the width of an int, which is why it is there.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development