C++ Program Structure

Next Article


C++ is a very popular programming language. Every C++ program has a general structure like in the following figure.


C++ Program Structure
C++ Program Structure

Header Section

The header section is used for

  1. including header files
  2. declaring global variables
  3. declaring functions
  4. defining constants

In C++, there are many functions that do different types of tasks. Some functions are builtin and some are user defined functions.Builtin functions are written in a header file that ends with a .h extension.

The syntax to include a header file is #include “iostream.h” or #include .When we use
double quotes the compiler look for this header file in the directory where the C++ program located and then look for file in Include directory that contains all the headers.Otherwise, if we use < ….> , then compiler look for the file under Include directory.

In header section , we can declare a new function

void add() ;

int calculate();

We can also declare global variable that can be used by entire program.

int number;

char name;

Sometimes, we want to declare a numeric constant value. The syntax to declare a numeric constant whose value does not change is

#define MAX 10

#define PI  3.14 

The Main Function

The main function is where your program gets executed first. The main function has a default type of integer in C++. It calls other functions while executing.

void main() {

statement 1;

statement 2;



In the main function, you start writing your program after the opening braces { and  when you finished writing then close the brace with a closing brace }.Every C++ statement ends with a semi-colon.

If the main function does not return any value, you can change the function type to void.

Other Functions

If your program contains other functions then each function definition comes after the main function.

The function is declared within main() or in the header section. But the definition of function comes after the main function.

Putting it all together

The following is an example of C++ program structure.

#include <iostream>
#define NUM 100
 void main()
 int x = 20;
int sum = 0;
sum = x + NUM;
cout << sum << endl;


Next Article