Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>C and C++ can run on many different architectures, and machine types. Consequently, they can have different representations of numbers: Two's complement, and Ones' complement being the most common. In general you should not rely on a particular representation in your program.</p> <p>For unsigned integer types (<code>size_t</code> being one of those), the C standard (and the C++ standard too, I think) specifies precise overflow rules. In short, if <code>SIZE_MAX</code> is the maximum value of the type <code>size_t</code>, then the expression</p> <p><code>(size_t) (SIZE_MAX + 1)</code></p> <p>is guaranteed to be <code>0</code>, and therefore, you can be sure that <code>(size_t) -1</code> is equal to <code>SIZE_MAX</code>. The same holds true for other unsigned types.</p> <p>Note that the above holds true:</p> <ul> <li>for all unsigned types,</li> <li><em>even if the underlying machine doesn't represent numbers in Two's complement</em>. In this case, the compiler has to make sure the identity holds true.</li> </ul> <p>Also, the above means that you can't rely on specific representations for <em>signed</em> types.</p> <p><em>Edit</em>: In order to answer some of the comments:</p> <p>Let's say we have a code snippet like:</p> <pre><code>int i = -1; long j = i; </code></pre> <p>There is a type conversion in the assignment to <code>j</code>. Assuming that <code>int</code> and <code>long</code> have different sizes (most [all?] 64-bit systems), the bit-patterns at memory locations for <code>i</code> and <code>j</code> are going to be different, because they have different sizes. The compiler makes sure that the <em>values</em> of <code>i</code> and <code>j</code> are <code>-1</code>.</p> <p>Similarly, when we do:</p> <pre><code>size_t s = (size_t) -1 </code></pre> <p>There is a type conversion going on. The <code>-1</code> is of type <code>int</code>. It has a bit-pattern, but that is irrelevant for this example because when the conversion to <code>size_t</code> takes place due to the cast, the compiler will translate the <em>value</em> according to the rules for the type (<code>size_t</code> in this case). Thus, even if <code>int</code> and <code>size_t</code> have different sizes, the standard guarantees that the value stored in <code>s</code> above will be the maximum value that <code>size_t</code> can take.</p> <p>If we do:</p> <pre><code>long j = LONG_MAX; int i = j; </code></pre> <p>If <code>LONG_MAX</code> is greater than <code>INT_MAX</code>, then the value in <code>i</code> is implementation-defined (C89, section 3.2.1.2).</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