Hello World
suggest change#include <iostream>
int main()
{
std::cout << "Hello World!" << std::endl;
return 0;
}
Hello World!
Let’s examine each part of this code in detail.
#include <iostream> is a preprocessor directive that includes the standard C++ header file iostream.
iostream is a standard library header file that contains definitions of the standard input and output streams. These definitions are included in the std namespace.
The standard input/output (I/O) streams provide ways for programs to get input from and output to an external system -- usually the terminal.
int main() { ... } defines a function named main.
A hosted program starts at main. It has one main function, and that function's return type is int.
The value returned by main is an exit code. Returning 0 reports success. A non-zero exit code indicates an error.
std::cout << "Hello World!" << std::endl; prints Hello World! to the standard output stream:
std is a namespace, and :: is the scope resolution operator. It looks up a name in a given namespace.
There are many namespaces. Here, we use :: to show we want to use cout from the std namespace.
std::cout is the standard output stream object, defined in iostream. It prints to the standard output (stdout).
<< is, in this context, the stream insertion operator, so called because it inserts an object into the stream object.
The standard library defines the << operator to perform data insertion for certain data types into output streams. stream << content inserts content into the stream and returns the same, but updated stream. This allows stream insertions to be chained: std::cout << "Foo" << " Bar";
"Hello World!" is a character string literal. The stream insertion operator for character string literals is defined in file iostream.
std::endl is a special I/O stream manipulator object, also defined in file iostream. Inserting a manipulator into a stream changes the state of the stream.
The stream manipulator std::endl does two things: first it inserts the end-of-line character and then it flushes the stream buffer to force the text to show up on the console. This ensures that the data inserted into the stream actually appear on your console. (Stream data is usually stored in a buffer and then "flushed" in batches unless you force a flush immediately.)
An alternate method that avoids the flush is: std::cout << "Hello World!\n";
\n is the character escape sequence for the newline character.
The semicolon (;) ends this expression statement. An expression statement ends with a semicolon, and so does a class definition. A function body does not.