Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Unsigned intgers are an artifact from the past. This is from the time, where processors could do unsigned arithmetic a little bit faster. </p> <p>This is a case of <em>premature optimization</em> which is considered evil.</p> <p>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 <em>unsigned</em> (the upper half of a 64 bit register gets cleard if you move a 32 bit value into it).</p> <p>But I would recommend against using <em>unsigned</em> in any arithmetic at all, being it pointer arithmetic or just simple numbers.</p> <p><code>for( unsigned int i = foo.Length() - 1; i &gt;= 0; --i ) {}</code></p> <p>Any recent compiler will warn about such an construct, with <em>condition ist always true</em> or similar. With using a signed variable you avoid such pitfalls at all. Instead use <code>ptrdiff_t</code>.</p> <p>A problem might be the c++ library, it often uses an unsigned type for <code>size_t</code>, 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).</p> <p>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.</p> <p>One exception for using <code>unsigned</code> 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.</p> <blockquote> <p>The result will never be a negative value (as the section number, by the way). So why use a signed integer for this?</p> </blockquote> <p>Because you might want to compare the return value to a signed value, which is actually negative. The comparison should return <em>true</em> in that case, but the C standard specifies that the signed get promoted to an unsigned in that case and you will get a <em>false</em> instead. I don't know about ObjectiveC though.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload