Problem in using unsigned variable as a counter

S

Sumit Nathany

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?
 
J

jameskuyper

Sumit said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top