Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The C standard doesn't have very hard rules for what you're trying to do. Here's the paragraph in question, from Section <strong>6.3.1 Arithmetic operands</strong> (specifically Section <strong>6.3.1.4 Real floating and integer</strong>):</p> <blockquote> <p>When a finite value of real floating type is converted to an integer type other than <strong><code>_Bool</code></strong>, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.</p> </blockquote> <p>There's even a more specific footnote about the exact case you're asking about:</p> <blockquote> <p>The remaindering operation performed when a value of integer type is converted to unsigned type need not be performed when a value of real floating type is converted to unsigned type. Thus, the range of portable real floating values is <code>(−1, Utype_MAX+1)</code>.</p> </blockquote> <p><code>UtypeMAX+1</code> for your case is <code>256</code>. Your mismatched cases are all negative numbers. After the truncation, they're still negative and are outside the range (-1, 256), so they're firmly in the 'undefined behaviour' zone. Even some of the matching cases you've shown, where the floating point number is greater than or equal to <code>256</code>, aren't guaranteed to work - you're just getting lucky.</p> <p>The answers to your numbered questions, therefore:</p> <ol> <li>Yes, you were wrong.</li> <li>It's a compiler issue in the sense that your different compilers give different results, but since they're allowed to by the spec, I wouldn't really call that the compiler's fault.</li> <li>It depends on what you want to do - if you can explain that better, someone on SO community is almost certain to be able to help you out.</li> </ol>
 

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