#include <iostream>
int main()
{
std::cout << "Hello World!\n";
}
This is absolutely correct. The main()
function is a special case in that you do not have to return any value from it; if you reach the end of main()
without a return
a return value of 0
is assumed.
#include <iostream>
int main ()
{
std::cout « "Hello World!" « std::endl;
return 0;
}
First off, this is badly (inconsistently) indented.
Having a space between the function name and the (
of the parameter list is uncommon, but legal.
It also uses '«'
('\xab'
) instead of <<
, which might be a typo by you -- if it isn't, that is a syntax errror as '«'
is not understood by C++.
It is using std::endl
instead of \n
. This is a more difficult case.
Writing std::endl
to an ostream
does two things -- write a newline, and flush the output buffer. Whereas writing "\n"
is only guaranteed to write the newline; whether it flushes the buffer depends on the buffering policy of the stream.
Output streams can be unbuffered (every byte is written immediately), line buffered (buffer is flushed at every written newline or when full), or fully buffered (buffer is flushed if full or flushed explicitly).
Output streams are line-buffered by default unless the implementation can assert that the output is not an interactive device... which excludes your terminal (which is an interactive device).
Hence, whether you write std::endl
or "\n"
does not make a difference... except where it does. In this specific case, where you are exiting the program just after the std::cout
, it does not make a difference -- any output stream will be flushed before the program exits anyway.
The return 0;
is optional, as I said before. It does not hurt having it there, and personally I prefer writing it out just as to not rely on anything "specific" at that point and not to confuse readers who do not know about the implicit return 0
for main()
. Your mileage may vary.
Side note on main()
: In C, a function declared with empty parameter list could be called with any number of arguments. This is a leftover from the ancient K&R style. If you want to make sure a function can only be called without arguments, in C, you have to declare it with ( void )
as parameter list, i.e. int main( void )
. This is recommended practice.
In C++, int main()
and int main( void )
are the same thing, and writing out that void
is uncommon.