100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C++

Structure of a C++ Program

Understand the essential building blocks of a C++ program — headers, namespaces, the main function, and statements — with an annotated example.

Introduction to C++Beginner6 min readJul 7, 2026
Analogies

1. Intro

Every C++ program follows a predictable structure. Learning to recognize each part — header inclusions, namespaces, the main() function, and statements — makes it much easier to read, write, and debug C++ code.

🏏

Cricket analogy: Just as a Test match follows a fixed structure - toss, innings, overs, declaration - a C++ program follows a predictable structure of headers, namespaces, main(), and statements that you learn to recognize instantly.

2. Syntax

cpp
// 1. Preprocessor directive (header inclusion)
#include <iostream>

// 2. Namespace declaration
using namespace std;

// 3. Function declarations/definitions (main is mandatory)
int main() {
    // 4. Statements inside the function body
    cout << "Hello, World!" << endl;

    // 5. Return statement
    return 0;
}

3. Explanation

A C++ program is built from a few standard parts. Preprocessor directives, like #include <iostream>, run before compilation and insert the contents of header files so their declarations (such as cout) become available. The using namespace std; line brings the names defined in the std namespace — where the standard library lives — into scope, so you can write cout instead of std::cout. Every executable C++ program must have exactly one main() function; this is the entry point where execution begins. The body of main(), enclosed in curly braces { }, contains statements that are executed in order, each terminated by a semicolon. Finally, return 0; signals to the operating system that the program finished successfully; a non-zero return value conventionally indicates an error.

🏏

Cricket analogy: #include <iostream> is like a team management office delivering the full playing squad list before the toss, so names like cout are available; using namespace std; is like announcing you'll call players by first name only, skipping 'Team India's.'

4. Example

cpp
#include <iostream>
using namespace std;

int main() {
    int age = 21;
    cout << "My age is: " << age << endl;
    return 0;
}

5. Output

text
My age is: 21

6. Key Takeaways

  • A C++ program typically starts with preprocessor directives such as #include <iostream>.
  • using namespace std; allows using standard library names like cout without the std:: prefix.
  • Every executable C++ program must contain exactly one main() function as its entry point.
  • Statements inside main() run sequentially and each must end with a semicolon ;.

Practice what you learned

Was this page helpful?

Topics covered

#CStudyNotes#Programming#StructureOfACProgram#Structure#Program#Syntax#Explanation#StudyNotes#SkillVeris#ExamPrep