Egs on unsigned integer
#include
main(){
unsigned int i;
for(i=1;i>-2;i--)
printf("c aptitude");
}
Explanation:
i is an unsigned integer. It is compared with a signed value. Since the both
types doesn't match, signed is promoted to unsigned value. The unsigned
equivalent of -2 is a huge value so condition becomes false and control
comes out of the loop.
#include
int main()
{
unsigned giveit=-1;
int gotit;
printf("%u ",giveit);
printf("%u ",++giveit);
printf("%u \n",gotit=--giveit);
}
Answer
65535 0 65535
main()
{
signed char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}
Answer
-128
Explanation
Notice the semicolon at the end of the for loop. THe initial value of
the i is set to 0. The inner loop executes to increment the value
from 0 to 127 (the positive range of char) and then it rotates to the
negative value of -128. The condition in the for loop fails and so
comes out of the for loop. It prints the current value of i that is -128.
{
unsigned char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}
Answer
infinite loop
Explanation
The difference between the previous question and this one is that the char
is declared to be unsigned. So the i++ can never yield negative value and i>=0
never becomes false so that it can come out of the for loop.
main()
{
char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}
Answer:
Behavior is implementation dependent.
Explanation:
The detail if the char is signed/unsigned by default is
implementation dependent. If the implementation treats the char to be
signed by default the program will print –128 and terminate. On the other
hand if it considers char to be unsigned by default, it goes to infinite loop.
Rule:
You can write programs that have implementation dependent
behavior. But dont write programs that depend on such behavior.
0 comments:
Post a Comment