C++ Hello World Program


In this tutorial, you will learn about a simple C++ Hello World program with step by step explanation.

C++ Hello World Program

The Hello world program is the first step for learning any programming language as it covers the basics and is the simplest program. It just prints “Hello World” in the screen.

Here is the example of C++ program to print Hello World line by line explanation.

C++ Hello World Program

//"Hello, World!" program in C++

#include <iostream>
using namespace std;

int main()
{
   cout << "Hello, World!";
   return 0;
}

OR

C++ Hello World Program: Without including namespace

//"Hello, World!" program in C++

#include <iostream>

int main()
{
   std::cout << "Hello, World!";
   return 0;
}

Output

Both the programs above will yield the same output.

Hello, World!

Explanation

There are many similar things in C and C++.

Line 1:

//"Hello, World!" program in C++

This is a single line comment in C++. Everything in a line after double forward slash // is a comment.

Line 2:

#include <iostream>

Everything after hash # is called directives that are processed by preprocessor. The above line causes the compiler to include standard lines of C++ code, known as header iostream, into the program.

The file iostream contains definitions that are required for stream input or output i.e. declaration for the identifier cout and cin.

Line 3:

using namespace std;

This is a new concept introduced by ANSI C++ called namespace that defines the scope of the identifiers. std is the namespace where standard class libraries are defined.

The using keyword is used to include already defined namespace std into our scope.

If we didn’t include using the keyword, we have to use the following format:

std::cout << "Hello, World!";

Line 4:

int main()

Every C++ program must contain main function that contains actual code inside curly braces {}.

The return type of main function is of int type.

Line 5:

cout << "Hello, World!";

This line instructs the compiler to display the string inside quotation "" in the screen.

cout is an identifier which corresponds to the standard output stream whereas << is the insertion operation.

Line 6:

return 0;

This statement returns the value 0 which represents the exit status of the program.

This is all about the first program in C++.