About the use of signed integers in C family of languages

后端 未结 5 1036
一整个雨季
一整个雨季 2021-01-11 17:57

When using integer values in my own code, I always try to consider the signedness, asking myself if the integer should be signed or unsigned.

When I\'m sure the valu

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-11 18:29

    Unsigned intgers are an artifact from the past. This is from the time, where processors could do unsigned arithmetic a little bit faster.

    This is a case of premature optimization which is considered evil.

    Actually, in 2005 when AMD introduced x86_64 (or AMD64, how it was then called), the 64 bit architecture for x86, they brought the ghosts of the past back: If a signed integer is used as an index and the compiler can not prove that it is never negative, is has to insert a 32 to 64 bit sign extension instruction - because the default 32 to 64 bit extension is unsigned (the upper half of a 64 bit register gets cleard if you move a 32 bit value into it).

    But I would recommend against using unsigned in any arithmetic at all, being it pointer arithmetic or just simple numbers.

    for( unsigned int i = foo.Length() - 1; i >= 0; --i ) {}

    Any recent compiler will warn about such an construct, with condition ist always true or similar. With using a signed variable you avoid such pitfalls at all. Instead use ptrdiff_t.

    A problem might be the c++ library, it often uses an unsigned type for size_t, which is required because of some rare corner cases with very large sizes (between 2^31 and 2^32) on 32 bit systems with certain boot switches ( /3GB windows).

    There are many more, comparisons between signed and unsigned come to my mind, where the signed value automagically gets promoted to a unsigned and thus becomes a huge positive number, when it has been a small negative before.

    One exception for using unsigned exists: For bit fields, flags, masks it is quite common. Usually it doesn't make sense at all to interpret the value of these variables as a magnitude, and the reader may deduce from the type that this variable is to be interpreted in bits.

    The result will never be a negative value (as the section number, by the way). So why use a signed integer for this?

    Because you might want to compare the return value to a signed value, which is actually negative. The comparison should return true in that case, but the C standard specifies that the signed get promoted to an unsigned in that case and you will get a false instead. I don't know about ObjectiveC though.

提交回复
热议问题