Thread: signed/unsigned int

  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,897
    >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, 08: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-02-2003, 12:26 AM
  5. easy if you know how to use functions...
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 01-31-2002, 07:34 AM