Uint_max

This is a discussion on Uint_max within the C Programming forums, part of the General Programming Boards category; I was curious if it is safe to assume the following is true on all machines? Code: (unsigned int)-1 == ...

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    42

    Uint_max

    I was curious if it is safe to assume the following is true on all machines?
    Code:
    (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
    Posts
    14,826
    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.

    Example
    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:
    Code:
    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.

    Quzah.
    (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
    Posts
    9,796
    >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

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