Syntax of C++

Syntax of a programming language means the combination of various symbols and keywords to form a meaningful code.

According to Wikipedia –

“In computer science, the syntax of a computer language is the set of rules that defines the combinations of symbols that are considered to be a correctly structured document or fragment in that language. This applies both to programming languages, where the document represents source code, and to markup languages, where the document represents data.”

Let us look at a simple program that would print the message Hello World.

#include <iostream>
using namespace std;

// The execution of the program begins from the main function.

int main()
    cout << "Hello World";
    return 0;

When this program runs, the following message would be displayed.

Hello World

Let us understand various parts of the above program step by step

  • The first line ‘#include<iostream>’ is a preprocessor directive written to include the standard library iostream in our program. This is required because we need to use the cout object in our program. A preprocessor directive is a line starting with the sign # and is generally used to include other files in our program before the compilation starts.
  • The line ‘using namespace std’ is used here so that we can use all the things within ‘std’ namespace in our program. The std is abbreviated for ‘standard’. Namespaces are used to avoid naming conflicts. If you want to learn more about namespaces, visit this link namespace in C++.
  • If we do not use std namespace in our program, we need to use cout like this – std::cout.
  • The next line written after // is a single line comment. A comment is avoided by the compiler and would not be executed.
  • Next line int main() is the starting of the main function. From this point the execution of the program starts. The scope of a function is within the opening brace ‘{‘ and the closing brace ‘}’.
  • The next line cout<<“Hello World” displays the message “Hello World” on the output screen.
  • return 0 is the ending point point of the main function and of our program.

Things to remember

  • Every individual statement in C++ ends with a semicolon.
  • C++ does not recognize the end of a line as a terminator. So, it does not matter whether you put two different statements line by line or in the same line.

For Example

int x = 1;

is same as

int x = 1;cout<<x;
  • We need to include separate header files for using different functions and objects. For example to use standard mathematical functions, we need to include the header file ‘cmath’.

Leave a Comment

Your email address will not be published. Required fields are marked *