C++ Code Structure

For understanding the structure of the C++ code, first consider the following snapshot of the code.

#include<iostream>
using namespace std;
int main()
{
cout <<"Hello World";
return 0;
}

Output:

Hello World


The code consists of seven lines.  Each line of the code is called statement of expression. Each C++ statement ends with semicolon(;). We explain each statement of the code.

  1. #include <iostream.h>;

    The first line is #include <iostream.h>;.  In this line the “#” is called directive which give the instruction to the compiler. The word include written after with # tells the compiler to include a file named iostream whose extension is h. In fact iostream.h is the header file. All the header files in C++ have extensions .h. These header files contain definitions for the builtin functions. The header file iostream.h contains definitions for the functions which are mostly related to input/output therefore called iostream.  The symbols “<” and “>” are the part of the syntax. When ever we need to define header file in our code we will write in this a way. For example we can declare other header file #include<stdio.h>.

  2. using namespace std;

    The second line says using namespace std;. This line tell the compiler to use C++ standard library. All most all of the codes will contain this line. Whenever we need to use standard library of C++, we will have to use this line.  In fact the interface of the standard library of C++ is defined by collection of many header files. We will know about it later.

  3. int main()

    The third line is int main(). The word “main” defines that it is a main function. It tell the compiler to start running the code from this line after it has included all the header files. The parenthesis are the part of the main function definition. In fact within parenthesis we can pass different values/parameters. We will learn about this later. The first word “int” defines that the main function has to return some value whose type is integer. In fact at this position return type is written. There are other return types as well e.g. char, float, double etc.

  4. Opening Curly Bracket ({)

    The next line is the opening curly bracket. In fact, all the statements of function are enclosed within curly brackets. The last line is the closing bracket.

  5. cout <<“Hello World”;

    The fifth line prints the output “Hello world”.  The word “cout” means standard console output. The “<<” is the part of the syntax. It uses the “std” which we wrote earlier. In fact this send the console to output a stream.  

  6. return 0;

    This statement causes the function to return 0. It was necessary as we defined that the main function has to return any value of integer type.

  7. Closing Curly Bracket (})

    The last line completes all the statements of the main function.