Home > Article > Backend Development > Why does `func(\"one\")` cause an error in C implicit conversions?
C Implicit Conversions
In the context of C , the concept of implicit conversions has been a subject of discussion. A recent answer on "What other useful casts can be used in C ?" raised questions about the correct understanding of conversions in C .
Consider the following code snippet:
<code class="cpp">#include <string> struct A { A(const std::string &s) {} }; void func(const A &a) { } int main() { func("one"); // error func(A("two")); // ok func(std::string("three")); // ok }</code>
In this snippet, the first function call, func("one"), results in an error. This is because there is no direct conversion from a const char * to an A. While there is a conversion from a string to an A, using it would involve multiple implicit conversions, which is not permitted according to C standards.
The C Standard (SC22-N-4411.pdf) in section 12.3.4 "Conversions" states:
4 At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value.
This means that only one implicit user-defined conversion can be applied when performing a conversion. In the first function call, both the conversion from const char * to string and the conversion from string to A are user-defined conversions. Since more than one conversion is required, the compiler raises an error.
The above is the detailed content of Why does `func(\"one\")` cause an error in C implicit conversions?. For more information, please follow other related articles on the PHP Chinese website!