Structure of a C++ Program
In this section we will study the basic structure of a C++ program and get familiar with the key components that make up any program.
Basic program structure
Every C++ program consists of several key components:
Preprocessor directives
Preprocessor directives start with the # symbol and are processed before compilation begins:
In later modules we will get to know other libraries, such as <string> for working with strings and <vector> for working with collections of data. For now <iostream> is all we need.
Namespace
This line allows us to use standard C++ objects (such as cout, cin) without the std:: prefix. Without it we would have to write std::cout instead of cout.
The main() function
The main() function is the entry point of the program:
int— indicates that the function returns an integermain— the name of the function (required in every program)()— the parameter list (empty in this case){}— the function body, where the executable code livesreturn 0;— returns 0, meaning the program executed successfully
Operators and expressions
Inside the main() function we write operators and expressions:
Comments
Comments help explain the code and do not affect program execution:
Coding rules
1. Every statement ends with a semicolon ;
2. C++ is case-sensitive
Main and main are different names. A program without a lowercase main function will not run:
3. Spaces and line breaks are ignored by the compiler, but they affect readability — write neatly.
Both versions below are identical to the compiler, but not to a human:
4. Variable and function names may contain letters, digits, and underscores, but cannot start with a digit:
This basic structure is the foundation for all C++ programs we will study going forward.