DEV Community

Manzura07
Manzura07

Posted on

C++ syntax

This section lays out basic C++ syntax. The first step to learn any language is to study its rules and regulations which together are called as syntax. Formally, the term “Syntax” means an approved set of pre-defined protocols or rules that we need to follow while working in a programming language. Just like any other programming language, C++ has its own unique syntax.

So let us begin with a simple “Hello World!” program. Open any IDE or text editor and create file HelloWorld.cpp with following content.

// Basic header file for giving Input/output function
_#include <iostream>_
//Standard namespace
_using namespace std;_
//Entry point of the code 
_int main()_
{ 

           //Print Hello world on console and exit
             _cout<<"Hello world!"<<endl;_  
         _ return 0;_
}
Enter fullscreen mode Exit fullscreen mode

Line 1 is a comment for the reader as to that why we are including the iostream header file. Comments are ignored by the compiler. C++ ignores white space. Whitespace denotes blanks, tabs, newline characters and comments. Whitespace gives logical separation and is used by compiler to identify where one element in a statement ends, and the next element begins.

Line 2 tells compiler to include standard header iostream. Iostream is needed for input output functionality to a stream (console in this case). The compiler will look into the standard path for this. A user can include his own header file say XX.h that is located in same directory by simply writing #include “XX.h”

Line 3 is blank (kept blank for readability)

Line 4 is comment to denote we are using standard namespace

Line 5 tells compiler to use standard namespace in this file. Namespace is collection of names for objects and variables from the standard library. Namespaces allow us to group named entities into small and narrow scope that can be accessed privately for different programmes. This allows organizing the elements of programs into different logical scopes referred to by name. If you do not want to include standard namespace then you have to add std:: prefix before every standard object e.g. std::cout<<”…”;

Line 6 gives comment about main() to tell reader that it is the main entry point of this code. This means it is the first function that is called when the program executes

Line 7 starts definition of main(). Any code for a method that is written in {} gets executed.

Line 8 and 12 are curly brackets that enclose the body of main()

Line 9 gives comment

Line 10 uses cout function to print Hello world! On to console and then leave a line

Line 11 gives return statement with return code telling compiler to take control back from this program. Return code 0 denotes successful execution.

Top comments (0)