Ex - 1:What is the output?
main()
{
unsigned int i=10;
while(i-- >= 0)
printf("%u ",i);
}
Ans:
10 9 8 7 6 5 4 3 2 1 0 65535 65534…..
Explanation:
Since i is an unsigned integer it can never become negative. So the expression i-- >=0 will always be true, leading to an infinite loop. |
Ex - 2: What is the output?
#include
main()
{
int x,y=2,z,a;
if(x=y%2) z=2;
a=2;
printf("%d %d ",z,x);
}
Ans:
Garbage-value 0
Explanation:
The value of y%2 is 0. This value is assigned to x. The condition reduces to if (x) or in other words if(0) and so z goes uninitialized.
Thumb Rule: Check all control paths to write bug free code. |
Ex - 3: What is the output?
main()
{
unsigned int i=65000;
while(i++!=0);
printf("%d",i);
}
Ans:
1
Explanation:
Note the semicolon after the while statement. When the value of i becomes 0 it comes out of while loop. Due to post-increment on i the value of i while printing is 1. |