Note that there are some explanatory texts on larger screens.

plurals
  1. POUnsigned minus unsigned difference between 32 and 64-bit
    text
    copied!<p><strong>The situation:</strong><br> I have a piece of code that works when compiled for 32-bits but fails when compiled for 64-bits with gcc 4.6. After identifying the problem and reading up on the standards, I cannot really understand why it is working for 32-bits. I hope someone can explain what is going on.</p> <p><strong>The code (somewhat simplified and cut down to the interesting parts):</strong></p> <pre><code>// tbl: unsigned short *, can be indexed with positive and negative values // v: unsigned int // p: unsigned char * tmp = tbl[(v &gt;&gt; 8) - p[0]]; // Gives segfault when not compiled with -m32 </code></pre> <p>When compiled with <code>-m32</code> the code works. When compiled without <code>-m32</code> it gives a segfault. The reason for the segfault is that <code>(v &gt;&gt; 8) - p[0]</code> is interpreted as an <code>unsigned int</code> when compiled for 64-bit which for "negative" results will be way off.</p> <p>According to <a href="https://stackoverflow.com/q/8026694/713554">this</a> question, the C99 standard says the following:<br> 6.2.5c9: <code>A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.</code></p> <p>From this it seems that <code>unsigned</code> minus <code>unsigned</code> will always result in <code>unsigned</code> output which is consistent with what happens in the 64-bit case. This does not seem to happen in the 32-bit case which is what I find extremely strange.</p> <p>Can anyone explain what is happening in the 32-bit case?</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