Structure of a C++ program

Structure of C++ Program

A C++ program consists of declarations and definitions, organized into files that are combined through linking after separate compilation. It is divided into three main sections:

  1. Standard Libraries Section: This section contains the header files for the standard libraries that your program will use.
  2. Main Function Section: This section contains the main function, which is the entry point for your program.
  3. Function Body Section: This section can contain definitions for functions used in the program, including main.

Standard Libraries Section

#include <iostream>
using namespace std;
  • The #include directive is a preprocessor directive used to include header files in C++ programs. Header files are important in C++ because they store predefined functions and data types, which make programming easier. They can reduce the complexity and number of lines of code, and allow for reusing functions in different .cpp files.
  • <iostream> specifically imports the input-output stream library, which provides functionality for input and output operations in C++.
  • namespace std specifies that names like cout and endl are defined within the std namespace and can be used in the program.

Main Function Section

int main() {
    // Function body goes here
    return 0;
}
  • The main() function is the entry point of a C++ program, where execution begins.
  • The curly brace { marks the beginning of the main function body.
  • The curly brace } marks the end of the main function body.
  • It returns an integer value (int), typically 0 to indicate successful execution.

Function Body Section

 cout << "Hello, Everyone" << endl;
  • cout is used to display output to the console, and <<is the stream insertion operator.
  • "Hello, Everyone" is the text to be displayed, followed by endl to insert a newline and flush the output buffer.
  • return 0; terminates the main() function, returning 0 to the operating system to indicate successful execution.

Here is full code:

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

Output:

Hello, Everyone

This code demonstrates a simple C++ program that prints "Hello, Everyone" to the console.

How's article quality?

Last updated on -

Page Contents