Lesson content
Read, practise, then check your understanding
A C++ source file is a translation unit after preprocessing. Headers expose declarations; source files usually hold definitions. Identifiers are case-sensitive, statements normally end with semicolons, and braces create scopes that control name visibility and object lifetime.
Program structure
#include <iostream>
int square(int value); // declaration
int main() {
const int input{7};
std::cout << square(input) << '\n';
return 0;
}
int square(int value) { // definition
return value * value;
}
main returns an int; reaching its closing brace implies success. #include is a preprocessor directive, while std::cout is an object from the standard library. The std:: qualification says the name belongs to namespace std.
Expressions and statements
An expression computes a value or effect. An expression followed by ; becomes a statement. A declaration introduces a name and type. A compound statement { ... } groups statements and creates a block scope. Use // for a line comment and /* ... */ sparingly for block comments; comments should explain intent rather than repeat syntax.
Input and diagnostics
int age{};
if (std::cin >> age) {
std::cout << "Next year: " << age + 1 << '\n';
} else {
std::cerr << "Expected a number\n";
}
Stream extraction reports success through stream state. Always validate external input. Prefer consistent formatting, small scopes, one declaration per line when clarity benefits, and compile frequently so the first diagnostic stays close to its cause.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.