Sunday, December 6, 2009

Questions on operators (increment, relational)

1)
main()
{
int i=0;

while(+(+i--)!=0)
i-=i++;
printf("%d",i);
}
Answer:
-1
Explanation:
Unary + is the only dummy operator in C. So it has no effect on the
expression and now the while loop is, while(i--!=0) which is false
and so breaks out of while loop. The value –1 is printed due to the postdecrement
operator.


main()
{
float f=5,g=10;
enum{i=10,j=20,k=50};
printf("%d\n",++k);
printf("%f\n",f<<2);
printf("%lf\n",f%g);
printf("%lf\n",fmod(f,g));
}
Answer:
Line no 5: Error: Lvalue required
Line no 6: Cannot apply leftshift to float
Line no 7: Cannot apply mod to float
Explanation:
Enumeration constants cannot be modified, so you cannot apply ++.
Bit-wise operators and % operators cannot be applied on float values.
fmod() is to find the modulus values for floats as % operator is for ints.


main()

{
int i=5,j=10;
i=i&=j&&10;
printf("%d %d",i,j);
}
Answer:
1 10
Explanation:
The expression can be written as i=(i&=(j&&10)); The inner expression
(j&&10) evaluates to 1 because j==10. i is 5. i = 5&1 is 1. Hence the
result.



main()
{
int i=4,j=7;
j = j || i++ && printf("YOU CAN");
printf("%d %d", i, j);
}
Answer:
4 1
Explanation:
The boolean expression needs to be evaluated only till the truth value of
the expression is not known. j is not equal to zero itself means that the
expression’s truth value is 1. Because it is followed by || and true ||
(anything) => true where (anything) will not be evaluated. So the
remaining expression is not evaluated and so the value of i remains the
same.
Similarly when && operator is involved in an expression, when any of the
operands become false, the whole expression’s truth value becomes false
and hence the remaining expression will not be evaluated.
false && (anything) => false where (anything) will not be evaluated.



main()
{
register int a=2;
printf("Address of a = %d",&a);
printf("Value of a = %d",a);
}
Answer:
Compier Error: '&' on register variable
Rule to Remember:
& (address of ) operator cannot be applied on register variables.


No comments:

Post a Comment