Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   Problem in using unsigned variable as a counter (http://www.velocityreviews.com/forums/t641397-problem-in-using-unsigned-variable-as-a-counter.html)

 Sumit Nathany 10-24-2008 05:00 PM

Problem in using unsigned variable as a counter

Consider the code below:

unsigned int i=0;
for(j=1;j>-2; j--)
printf("Hello");

The printf statement is not executed even once. Why?

When the conditional statement in for loop is changed to j>=0 the
program goes into an infinite loop. Why?

 jameskuyper@verizon.net 10-24-2008 05:13 PM

Re: Problem in using unsigned variable as a counter

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.

 Sumit Nathany 10-24-2008 06:28 PM

Re: Problem in using unsigned variable as a counter

Thanks James! I will look for more co-operation from you in future.

 All times are GMT. The time now is 03:20 PM.