Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I wouldn't be all that surprised if somebody gets caught out by something like:</p> <pre><code>float ra[] = {0, CHAR_MAX, SHORT_MAX, INT_MAX, LONG_MAX}; </code></pre> <p>(on my implementation, the last two don't produce the same result when converted back to int/long, hence are narrowing)</p> <p>I don't remember ever writing this, though. It's only useful if an approximation to the limits is useful for something.</p> <p>This seems at least vaguely plausible too:</p> <pre><code>void some_function(int val1, int val2) { float asfloat[] = {val1, val2}; // not in C++0x double asdouble[] = {val1, val2}; // not in C++0x int asint[] = {val1, val2}; // OK // now do something with the arrays } </code></pre> <p>but it isn't entirely convincing, because if I know I have exactly two values, why put them in arrays rather than just <code>float floatval1 = val1, floatval1 = val2;</code>? What's the motivation, though, why that should compile (and work, provided the loss of precision is within acceptable accuracy for the program), while <code>float asfloat[] = {val1, val2};</code> shouldn't? Either way I'm initializing two floats from two ints, it's just that in one case the two floats happen to be members of an aggregate.</p> <p>That seems particularly harsh in cases where a non-constant expression results in a narrowing conversion even though (on a particular implementation), all values of the source type are representable in the destination type and convertible back to their original values:</p> <pre><code>char i = something(); static_assert(CHAR_BIT == 8); double ra[] = {i}; // how is this worse than using a constant value? </code></pre> <p>Assuming there's no bug, presumably the fix is always to make the conversion explicit. Unless you're doing something odd with macros, I think an array initializer only appears close to the type of the array, or at least to something representing the type, which could be dependent on a template parameter. So a cast should be easy, if verbose.</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