Thread: Uint_max

  1. #1
    Registered User
    Join Date
    Jan 2005


    I was curious if it is safe to assume the following is true on all machines?
    (unsigned int)-1 == UINT_MAX
    I'm guessing the answer is no, but I thought I'd be sure.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    C: A Reference Manual, 5th Edition, page 129:

    Whether an ingeger is signed or unsigned affects the operations performed on it. All
    arithmetic operations on unsigned integers behave according to the rules of modular (con-
    gruence) arithmetic modulo 2n. So, for example, addint 1 to the largest value of an unsigned
    type is guarinteed to produce 0. The behavior of overflow is well defined.
    Expressions that mix signed and unsigned integers are forced to use unsigned opera-
    tions. Section 6.4.3 discusses the conversions performed, and Chapter 7 discusses the
    effect of each operator when its arguments are unsigned.

    These conversions can be surprising. For example, because unsigned integers are always non-
    negative, you would expect that the following test would always be true:
    unsigned int u;
    if( u > -1 ) ...
    However, it is always false! The (signed) -1 is converted to an unsigned integer before the
    comparison, yielding the largest unsigned integer, and the value of u cannot be greater than
    that integer.

    The origional definition of C provided only a single unsigned type, unsigned. Most
    non-Standard C implementations now provide the full range of unsigned types.

    So yes.

    (ps: Any typos in the above are mine and were not in the book.)
    Hope is the first step on the road to disappointment.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    >I was curious if it is safe to assume the following is true on all machines?
    Yes, as long as you don't make any other assumptions, like bit count and representation.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed