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.
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"; }
Output
Hello World
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>
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)
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++.