c++endl

C++ endl not printing new line when called from a method


New to C++ My understanding is endl will add a new line. So with the following piece of code:

#include <iostream>

using namespace std;

void printf(string message);

int main()
{

cout << "Hello" << endl;
cout << "World" << endl;

printf("Hello");
printf("World");

return 0;

}

void printf(string message) {
cout << message << endl;
}

I expect the output to be:

Hello

World

Hello

World

But, strangely, the output is:

Hello

World

HelloWorld

Looks like, when called from the user-defined method, endl is not adding new line..?? What is wrong with my understanding here. Please advise.


Solution

  • The problem is that due to overload resolution the built in printf function is selected over your custom defined printf function. This is because the string literal "Hello" and "World" decays to const char* due to type decay and the built in printf function is a better match than your custom defined printf.

    To solve this, replace the printf calls with :

    printf(std::string("Hello"));
    printf(std::string("World"));
    

    In the above statements, we're explicitly using std::string's constructor to create std::string objects from the string literal "Hello" and "World" and then passing those std::string objects by value to your printf function.

    Another alternative is to put your custom printf inside a custom namespace. Or you can name your function other than printf itself.