Why this is ok?

Cnks 21 Reputation points

in my book: C++ primer plus , it says that
long plifs[] = {25,92,3.0};
is not allowed.

but I can use it.

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
2,894 questions
{count} votes

Accepted answer
  1. Jeanine Zhang-MSFT 5,821 Reputation points Microsoft Vendor


    As far as I'm concerned you couldn't ignore the warning generated by the compiler. Here the compiler will generate Compiler Warning (level 1) C4838 .

    In general, for violations of the language rules, the C++ standard requires that the compiler issue a diagnostic. It did that. The Standard specifies that a diagnostic is required in case that a program is ill-formed. Which is the case when a narrowing-conversion takes place inside a braced-initializer.

    According to the Doc: Implicit type conversions

    If the selected conversion is a promotion, the compiler does not issue a warning. If the conversion is a narrowing, the compiler issues a warning about possible data loss. Whether actual data loss occurs depends on the actual values involved, but we recommend that you treat this warning as an error.

    Best Regards,

    Jeanine Zhang

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

1 additional answer

Sort by: Most helpful
  1. Michael Taylor 41,551 Reputation points

    The book is wrong if it says that is not OK. Not sure what the book says is not valid about this but it has always been valid in C++. The array is implicitly sized because you didn't specify the size in the declaration. Therefore it'll use the size of the array you're assigning to it (which is required). Curly braces with values separated by commas indicates an array. You are assigning the 3 element array to the plifs array. Therefore that array will have an implicit size of 3.

    The only thing that remotely stands out as potentially an issue is the last element in the array is a double. This requires the compiler to truncate the double to a long. In C this was allowed for array initialization and therefore C++ allows it as well. However C++ will generate a warning letting you know that you're potentially losing data. It is important to always look at compiler warnings to ensure they may not be indicating something is wrong with your code. Many companies have a "clean build" policy when it comes to warnings for good reasons.

    1 person found this answer helpful.