signed/unsigned int

This is a discussion on signed/unsigned int within the C Programming forums, part of the General Programming Boards category; Ill get to the point why cant i do: for (unsigned int i = 4; i >= 0; i--) but ...

  1. #1
    Registered User
    Join Date
    Aug 2003
    Posts
    288

    signed/unsigned int

    Ill get to the point

    why cant i do:

    for (unsigned int i = 4; i >= 0; i--)

    but i can do

    for (int i = 4; i >= 0; i--)

    if i try the first line, it counts down from 4.2 billion or something

    what i dont understand is why only the second one works, an unsigned int can have a value of 4 without
    overflowing and so can a signed integer, but why doesnt it work with unsigned integers?

    is it a bug? or am i doing something wrong?

    [EDIT] Compiler is MSVC 6

  2. #2
    Registered User
    Join Date
    Jun 2004
    Posts
    23
    The for loop first works at carrying out the the mathematical operation of "i--" and then checks the condition of i>=0

    When you make is unsigned and then when i =0 after that it once again performs i = i -1 so in this case i = 0-1 .
    Now since you have it as unsigned it creates problems by genrating random outputs.

    if you keep (unsigned int i =4;i>0;i--)
    There should be no problem

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Now since you have it as unsigned it creates problems by genrating random outputs.
    There's nothing random about it. Unsigned underflow wraps around to the largest value for the type. The problem is that the loop is infinite because an unsigned integer cannot hold a value less than 0 whereas a plain integer, which is signed, can. The behavior is well defined, so the following loop is incorrect:
    Code:
    for (unsigned i = n; i >= 0; i--)
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    Aug 2003
    Posts
    288
    Aha i didnt think of that, thanks guys

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. Replies: 2
    Last Post: 03-24-2006, 07:36 PM
  3. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM
  4. Quack! It doesn't work! >.<
    By *Michelle* in forum C++ Programming
    Replies: 8
    Last Post: 03-01-2003, 11:26 PM
  5. easy if you know how to use functions...
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 01-31-2002, 06:34 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21