C++ Hello World Program Output |
C++ is one of the most popular and powerful programming languages in the world. In this short article, we are going to go back to the basics and take a look at the simplest of the C++ program - the "Hello World" program which prints "Hello World!" to the screen.
While you can set up a C++ environment very easily using one of the IDEs (including free ones such as CodeBlock or Eclipse), we'll be using a free online C++ compiler (or runner) for the sake of keeping things very simple and straightforward.
C++ Hello World Program Code
#include <iostream> int main() { // Comment std::cout << "Hello World!"; return 0; }
Line-by-line Explanation
- C++ is a vast and very flexible language and a lot of functionality is offered by different libraries which we can include at the start of the program depending on what we need to do. Anything starting with a pound sign
#
is called a preprocessor directive. Theiostream
file is in the standard C++ library and comes with it. Here it is included so that we can use thestd::cout
functionality. - Blank Line
- Every C++ program no matter how small or large must have a
main()
function defined. This is the default function that the C++ compiler calls internally when executing a program. Theint
precedingmain()
declares that the function must return anint
or integer value (often back to the operating system or program that runs it). And, you can see that the 6th line indeed does return an integer (0). The opening curly brace{
starts the function block while the closing}
on the 7th line closes it. - Anything after double-forward backslashes is a comment which is ignored by the compiler. Real-world code contains a lot of comments that the programmers and often the whole team uses to mark and identify what parts of the code do. Having a well-commented code is considered good practice.
std::cout << "Hello World!";
line is what actually prints the line "Hello World!" to the screen. The whole line is what we call a statement in C++ and like many other programming languages must be ended with a semi-colon (;).- It returns an integer value (see line 3) which is called the Exit Code of the program.
- Closes the function block (see line 3)
Summary
main()
function is required in any C++ program, this is the block of code where the execution of the program starts.- C++ is an extensive and flexible programming language, a lot of standard functions of the language are provided in the form of C++ Standard Library.
iostream
included in the above program is part of this library. iostream
offers input/output functionality and we include it whenever we need such capabilities.- The very basic and bare structure of a C++ is as follows (note that it does nothing):
int main() { return 0; }