Skip to content

Chapter 2 of 31

Basic Syntax and Structure

Understand translation units, main, declarations, expressions, blocks, and console I/O.

24 minutes 10 quick checksBy Subha Prasad
Lesson 2 of 31Course navigation

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.

What is the standard C++ program entry point?
Which statement writes to standard output?
What does :: mean in std::cout?
Which comment runs to end of line?
What normally ends a C++ statement?
Which header declares std::cout?
What is a translation unit?
What does return 0 from main report?
Which braces create a block scope?
Why avoid using-directives in headers?

0 of 10 checks passed

Your progress is saved on this device.