Discussion
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int y = 1;
if (y & (y = 2))
printf("true %d\n", y);
else
printf("false %d\n", y);
}
Answer: A
Correct answer: true 2
& is the bitwise AND, so unlike && it does not short-circuit and both operands are evaluated. The assignment sets y to 2 and yields 2, so the test is a non-zero value and the true branch runs, printing the current value of y, which is now 2.
One caution is worth stating: reading y in the left operand is unsequenced with respect to the assignment in the right, which the C standard leaves undefined. Compilers in practice produce true 2, but the expression is one to recognise as badly formed rather than to imitate.
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