C++ Program Syntax

In this lesson, you will learn about the basic Syntax of a C++ program: libraries section, main() function, and function body, with examples, to better understand the topic.

Your first C++ Program

The program below is the famous “Hello World” application, which prints the sentence “Hello World” to the output.

Hello World Program in C++
This program takes no input from the user

#include <iostream>

using namespace std;

int main() {
  std::cout << "Hello World";


Hello World

C++ Program elements

1- C++ Program Libraries Section

A C++ program starts with the library section, where all libraries and namespaces for the program to run correctly are defined.

The program above requires the <iostream> library to function correctly. It’s attached to the program by using the #include keyword:

#include <iostream>
A C++ program can have more elements, such as Constructors, Destructors, and Variables. You will learn about these elements in the next few lessons.

2 – C++ Program Main Function

The main() function is the entry point for any C++ program. Without the main() function, your program will throw the error:

undefined reference to ‘main’

You can create the main() function to accept parameters.

int main(Datatype arg)

3 – C++ main() function Body

In C++, a function or method starts and ends with curly brackets {}

int main() {
std::cout << "Hello World";

If you miss one bracket, your program will throw an error:

error: expected ‘}’ at end of input

This concludes the Syntax of the C++ program lesson. In the next lesson, you will learn about the different types of Comments in C++.