Search code examples
c++initializationlanguage-lawyerdeclarationimplicit-conversion

Is initializing char array from string literal considered to be a implicit conversion?


Is char x[10] = "banana"; considered to be a implicit conversion from const char[7] to char[10]?

Since std::is_convertible<const char[7], char[10]>::value evaluates to false the obvious answer would be that it isn't, but I couldn't find a proper definition of implicit conversion anywhere. Reading cppreference I'd say that it is because:

Implicit conversions are performed whenever an expression of some type T1 is used in context that does not accept that type, but accepts some other type T2; in particular: ... when initializing a new object of type T2, including return statement in a function returning T2;

although I'm not sure why they didn't exclude explicit constructors from this case.

Follow-up question (which may be useless):

Are arrays completely excluded from any kind of conversions (meaning array-to-array conversions) ?


Solution

  • Language-lawyerly speaking, initializing char array from string literal is a implicit conversion.

    [conv.general]:

    An expression E can be implicitly converted to a type T if and only if the declaration T t=E; is well-formed, for some invented temporary variable t ([dcl.init]).

    Note that the core language only defines implicit conversion from an expression to a type. So the meaning of "implicit conversion from const char[7] to char[10]" is undefined.

    is_convertible<From, To>::value is false whenever To is an array type, because it is defined to produce false if To is not a valid return type, which an array is not. (This can be implemented in different ways.)

    [meta.rel]/5:

    The predicate condition for a template specialization is_­convertible<From, To> shall be satisfied if and only if the return expression in the following code would be well-formed, including any implicit conversions to the return type of the function:

    To test() {
      return declval<From>();
    }
    

    Arrays can rarely be the destination of implicit conversions, since they can be neither parameter types nor return types. But they are not excluded from temporary materialization conversion.