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 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.

By convention, the main function is where the program starts. There can be only one main function in a C++ program, and it must return a number of the int type.

int is function's return type The value returned by the main function is an exit code.

By convention, exit code of 0 is success. 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 object by 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 (;) notifies the compiler that a statement has ended. All C++ statements and class definitions require an ending/terminating semicolon.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents