Problem in using unsigned variable as a counter

Discussion in 'C Programming' started by Sumit Nathany, Oct 24, 2008.

  1. 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?
    Sumit Nathany, Oct 24, 2008
    #1
    1. Advertising

  2. Sumit Nathany

    Guest

    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.
    , Oct 24, 2008
    #2
    1. Advertising

  3. Thanks James! I will look for more co-operation from you in future.
    Sumit Nathany, Oct 24, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. The Eeediot
    Replies:
    3
    Views:
    2,230
    =?Utf-8?B?UnVsaW4gSG9uZw==?=
    Dec 22, 2004
  2. Timo Freiberger
    Replies:
    3
    Views:
    943
    Bob Hairgrove
    Oct 30, 2004
  3. George Marsaglia

    Assigning unsigned long to unsigned long long

    George Marsaglia, Jul 8, 2003, in forum: C Programming
    Replies:
    1
    Views:
    674
    Eric Sosman
    Jul 8, 2003
  4. George2
    Replies:
    1
    Views:
    796
    Alf P. Steinbach
    Jan 31, 2008
  5. pozz
    Replies:
    12
    Views:
    738
    Tim Rentsch
    Mar 20, 2011
Loading...

Share This Page