which one of these is correct and does it matter?

#include <iostream>

using namespace std;

int main(){
cout << "hello world" << endl;

return 0;
}

or is this one correct?

#include <iostream>

int main(){

std::cout << "hello world\n";


return 0;
}

sorry if i am being stupid i am just trying to learn stuff. thanks.
This
1
2
cout << "hello world" << endl;

is, by definition, exactly the same as
1
2
cout << "hello world" << '\n' << flush;

or, if you like,
1
2
cout << "hello world" << '\n';
cout.flush();


They are both correct, but endl is redundant in this case since cout.flush() is called two lines below, when main() ends. (it is also called on any input from cin, and at other times).

As for whether it matters, it does not usually mater for screen output (endl is only a little slower), but when writing to a file, unnecessary flushing makes the output much slower.

Stroustrup uses \n in his books even for screen output (see here for example http://www2.research.att.com/~bs/3rd_code.html ), and it's generally considered better style.

Alexandrescu called the abuse of endl "the endl fiasco", but I think he was talking more about the failure of C++ education in general.
Last edited on
They are both correct, and in a sense it doesn't really matter. The main issue is, of course, the using namespace std; bit.

What this does is takes all of the contents of the std namespace and "dumps" it into the global namespace; for simple programs this doesn't really matter but if, say, you were writing a header for your library you wouldn't ever want to do that. If you did, anyone using your header would immediately have the std namespace imported into the global one, possibly giving them unexpected results.
Thank you Zhuge thats all that i was wondering also thx to cubbi for explaining the new line and end line i did not know that it was slower.
Topic archived. No new replies allowed.