The parts of a C++ program are a small and learnable set. There are preprocessor directives, there are declarations, and there are statements and blocks, and they are grouped inside functions, with exactly one of those functions named main acting as the entry point. Once you can name each piece of a file out loud, code stops being a wall of characters and starts being a structure you can navigate.
The previous lesson in this module covered "How Do You Compile and Run C++ From the Command Line?", and this lesson is the last one in the Getting Started module.
The layers of a C++ program
A source file is built in layers, from the outside in.
-
Preprocessor directives are the lines that begin with a hash, such as
#includeand#define. They are handled before the compilation proper, and they are not really C++ code. - Declarations introduce names. Functions, variables, types and namespaces are all declarations.
- Statements are the instructions, and a statement ends with a semicolon.
- Blocks are groups of statements inside braces, and they also create a scope.
The top level structure of a program is a sequence of declarations and definitions. The function definitions contain blocks of statements. That hierarchy is all a beginner needs to hold in their head.
#include <iostream> // layer 1: preprocessor directive
double to_fahrenheit(double c) { // layer 2: declaration of a function
return c * 9.0 / 5.0 + 32.0; // layer 4: block containing one statement
}
int main() { // layer 2: the entry point
double celsius = 21.5; // layer 3: a declaration with a statement
std::cout << to_fahrenheit(celsius) << " F\n"; // layer 3: an expression statement
return 0;
}Statements, expressions and the semicolon
A statement is an instruction that does something. The simplest statement is the expression statement, which is an expression followed by a semicolon. In the line above, to_fahrenheit(celsius) is an expression, which is something that produces a value, and the whole line is a statement that prints it.
The semicolon is not decoration. It is the token that tells the compiler "this instruction ends here". Leave it out and the parser keeps consuming the next line looking for the end of the statement, and that produces a cascade of errors that point at the wrong place.
The main categories of statement that you will meet early are expression statements, declarations with an initialiser, the if and the loop statements, the return statements, and switch. Each one is a complete instruction with its own syntax rules.
Blocks and scope
A block is a set of statements wrapped in braces. Blocks do two jobs at once. They group statements so that they can be used as a unit, and they introduce a scope, which means that the names declared inside are only visible inside.
#include <iostream>
int main() {
int temperature = 18;
{
int temperature = 25; // shadows the outer variable
std::cout << "inside: " << temperature << '\n';
}
std::cout << "outside: " << temperature << '\n';
return 0;
}The inner value wins inside the block, and the outer value is intact afterwards.
inside: 25
outside: 18The inner temperature shadows the outer one for the duration of the inner block. The outer variable is untouched, and it comes back into view when the block ends. Shadowing is legal and it is occasionally useful, but it is also a classic source of confusion, so a different name is usually the clearer choice.
Notice that the scope rule applies to names and not to values. The inner block did not destroy or modify the outer variable. It simply introduced a different name that happened to look the same.
Names, whitespace and formatting
Identifiers are the names that you choose for variables, functions and types. They may contain letters, digits and underscores, and they may not start with a digit. They are case-sensitive, so count and Count are two different names.
Beyond that, C++ is almost entirely free-form about layout. The compiler does not care where you put spaces, so you can write a whole program on one line. You should not, though, because humans read the code.
#include <iostream>
int main()
{
int readings = 3;
double average = 21.5;
std::cout << "averaging " << readings << " readings\n";
if (average > 20.0)
{
std::cout << "warm: " << average << '\n';
}
else
{
std::cout << "cool: " << average << '\n';
}
return 0;
}The output confirms that both branches produce exactly one line, and that the braces changed nothing about the behaviour.
averaging 3 readings
warm: 21.5Two conventions are worth adopting straight away. Put the opening brace of a function on its own line, and put the braces of control flow statements on the same line as the keyword. That is the style used by the C++ Core Guidelines and by most modern codebases. And never skip the braces around a single statement, even when the statement is one line, because adding an extra line later and forgetting the braces is a bug that the compiler will happily accept.
Comments and what they are for
A comment is ignored by the compiler, and it exists purely for the reader. C++ gives you three forms.
// Line comment: good for a note attached to one line of code.
/*
Block comment: good for a paragraph of explanation that
should not sit in the middle of a dense piece of logic.
*/
/**
Documentation comment: picked up by documentation tools
to describe a function, its parameters and its result.
*/
int main() {
return 0;
}The rule of thumb is to comment the intent and not the mechanics. Writing "// increment i" above the line i++; adds nothing. Writing "// skip the header row" above a line that reads a CSV header does.
Where a program starts and ends
Execution begins at main, and nothing runs before it. Code at namespace scope that is not inside a function is either a declaration or a definition. A definition, such as a global variable, is initialised before main starts, but no other statement executes until main is entered.
That is why global variables with initialisers that call functions are legal but surprising. The initialiser runs before main exists to catch failures. It is better to do the work inside main and to pass the results around explicitly.
Quick reference
- A file is preprocessor directives, then declarations and definitions, and then statements inside blocks.
- Exactly one function is the entry point, and that is
int main(). - A statement ends with a semicolon, and a block is statements wrapped in braces.
- Braces create a scope, and the inner names shadow the outer ones.
- Indentation is for humans and not for the compiler, but keep it consistent and always use braces.
- Comments should explain the intent, because the code already explains the mechanics.
Try it yourself: take the temperature converter from the previous lesson and label every line with a comment that says whether it is a directive, a declaration, a statement or part of a block. Then move the conversion into a named function, and finally convert every single statement body to the braced form and confirm that the output is unchanged.