C++ Basic Syntax

The basic syntax rules of the C++ programming language are as follows –

1. Command terminator

C++ uses semicolon ; as the command terminator just like the C language. That means every statement must end with a semicolon. For example, following are two different code statements −

cout << "Hello ";
cout << "TechGuru!";
2. C++ block

A block is a set of logically related code statements that are surrounded by opening and closing brackets. For example −

   cout << "Hello TechGuru!"; // prints Hello TechGuru!
   return 0;
3. Multiple statements in a single line

We can write more than one separate executable statements in a single line, we should use a semicolon ; to separate these statements. As because, C++ does not recognize the end of the line as a terminator. For example −

cout << "Hello ";  cout << "TechGuru!";
4. Excluding Namespace

Our application may also exclude the standard namespace library. To do this, we have to omit the header using namespace std and replace it with the std keyword, followed by the scope resolution operator :: for some objects.

See the example code below.

#include <iostream>

int main() {
   std::cout << "Hello from TechGuru!";
   return 0;
5. Comments in C++

A comment is added to increase the readability of the program and it is of two types: single-line and multi-line.

C++ compiler completely ignores the comments. See the example below.
// This is single-line comment

/* C++ comments can span
   multiple lines */
6. Whitespace in C++

A line containing only whitespace, perhaps with a comment, is known as a blank line, and C++ compiler completely ignores it.

Whitespace is the term used in C++ to describe blanks, tabs, newline characters and comments.

It enables the compiler to separate one part of a statement from another. For example −

int sum;
sum = a + b;  //calculate sum