Home  >  Article  >  Backend Development  >  Why Does My C Code Print \"True\" Instead of \"Hello World\"?

Why Does My C Code Print \"True\" Instead of \"Hello World\"?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 03:51:02380browse

Why Does My C   Code Print

String Literal Matching Boolean Overload Instead of std::string

Consider the following C code:

<code class="cpp">class Output
{
public:
    static void Print(bool value)
    {
        std::cout << (value ? "True" : "False");
    }

    static void Print(std::string value)
    {
        std::cout << value;
    }
};</code>

When calling the method as follows:

<code class="cpp">Output::Print("Hello World");</code>

You may be surprised to see the output:

True

Why did the boolean overload of the Print method get called instead of the std::string overload?

Understanding the Conversion Mechanism

String literals in C , such as "Hello World", are stored as arrays of const characters. However, they can be implicitly converted to pointers to const characters, which can then be converted to bool.

In the provided code, the compiler prefers the standard conversion sequence from "Hello World" to bool over the user-defined conversion sequence from "Hello World" to std::string. This preference is based on the C standard, which states that standard conversion sequences take precedence over user-defined conversion sequences.

Resolving the Issue

To ensure that the std::string overload is called, explicitly pass an std::string argument:

<code class="cpp">Output::Print(std::string("Hello World"));</code>

By doing so, you force the compiler to use the std::string overload, which will correctly output "Hello World".

The above is the detailed content of Why Does My C Code Print \"True\" Instead of \"Hello World\"?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn