Sumit Nathany wrote:
Consider the code below:
unsigned int i=0;
for(j=1;j>-2; j--)
printf("Hello");
Your code sample contains a declaration for 'i', but never uses it. It
uses 'j', but never declares it.
I'll presume that you intended 'i' and 'j' to be the same.
The printf statement is not executed even once. Why?
When j==1, the comparison expression 'j>-2' is evaluated by first
converting '-2' to an unsigned integer, so that it can match the type
of j. The value of (unsigned int)(-2) is UINT_MAX-1, a number
guaranteed to be greater than 1. As a result, the condition for your
loop is never met, so the body of the loop is never executed.
When the conditional statement in for loop is changed to j>=0 the
program goes into an infinite loop. Why?
When j==0, what is the value of j-1? If your answer to that question
doesn't make it clear why your loop is failing, then you're answer to
that question is incorrect.