01 C++ Fundamentals and Program Structure
A structured introduction to C++ program organization, translation, language elements, and basic console input and output.
Program anatomy and entry point
A C++ program is built from declarations and definitions stored in source files and, commonly, header files. A minimal program has an entry point named main:
#include <iostream> makes standard input/output declarations available. int main() defines the function where execution begins, and return 0; reports successful completion. Braces delimit a block, while semicolons commonly terminate statements.
The prefix std:: qualifies names from the standard library's std . For example, writes output, and reads input.
Takeaway: Identify the entry point, included facilities, blocks, statements, and standard-library qualifications before tracing what a program does.
Files, translation, and building
A larger project can divide declarations and shared definitions between header files and implementations in .cpp source files. For example, a header may declare void say_hello();, while a source file defines that function and includes the header.
The #include directive is handled before ordinary . Conceptually, the included contents become part of the source being processed. The resulting source is a , which can be compiled independently from other translation units.
A typical build follows this progression:
Preprocessing handles directives such as
#includeand conditional .checks syntax and meaning and commonly produces an object file.
combines object files and libraries into an executable.
Execution loads and runs that executable.
With GCC, a complete single-file build can use g++ -std=c++17 -Wall -Wextra main.cpp -o main. The -c option stops after , allowing separate object files to be linked later.
Takeaway: Separate source files are compiled independently, then connects their definitions and library dependencies.
Comments, tokens, and names
Comments explain intent and are ignored during translation. A line comment begins with // and continues to the line's end. A block comment begins with /* and ends with */, so it may span multiple lines.
Whitespace includes spaces, tabs, and line breaks. It generally separates tokens but does not change the meaning of valid code. For example, int total = 3 + 4; and int total=3+4; have the same meaning, although the first form is easier to read.
A token is a meaningful lexical unit. Common categories include identifiers, keywords, literals, operators, and punctuators.
An names an entity such as item_count, calculate_area, or Rectangle. Ordinary identifiers begin with a letter or underscore, may contain digits after the first character, and are case-sensitive. Avoid implementation-reserved underscore forms and prefer descriptive names.
Keywords have predefined language meanings and normally cannot be used as identifiers. For example, class is a keyword, so int class; is invalid.
Takeaway: Formatting supports human readers, while tokens and their language rules determine whether the compiler can interpret the program.
Values, expressions, and statements
A writes a value directly in source code. Examples include the integer 42, floating-point 3.14, character 'A', string "C++", Boolean true, and null pointer nullptr. Integer literals may use decimal, hexadecimal such as 0x2A, or binary such as 0b101010 notation. Suffixes such as L, f, and u communicate type or representation preferences.
An produces a value, performs an operation, or does both. Examples include 2 + 3, width * height, and number = 10. Operators combine or transform operands: + adds, = assigns, and > compares. Parentheses can make grouping explicit, as in (a + b) * c.
A specifies an action or control operation. int count = 0; is a declaration , << count; is an , and return 0; is a jump . Braces create compound statements that contain other statements. Selection statements such as if and iteration statements such as while control which statements execute.
A character represents one character, whereas a string represents a sequence of characters. Escape sequences such as \n represent special characters inside character and string literals.
Takeaway: Distinguish values written directly in code, value-producing expressions, and statements that organize execution.
Console streams and input handling
The <iostream> header provides standard console streams. sends formatted output, reads formatted input, std::cerr is commonly used for diagnostics, and std::clog is intended for logging.
Output uses the insertion operator <<:
<< "Apples: " << apples << '\\n';inserts text, a variable, and a newline.\nmoves output to the next line.std::endlinserts a newline and flushes the stream, so\nis often preferable when an immediate flush is unnecessary.
Input uses the extraction operator >>. If age is an integer, >> age; attempts to read an integer and stores it in age. Extraction skips leading whitespace and interprets input according to the destination type.
For a line that may contain spaces, use std::getline(, name). After formatted extraction, a newline may remain in the input buffer. A common remedy is std::getline( >> std::ws, line), where std::ws consumes leading whitespace first.
Stream operations can fail. Testing if ( >> value) lets a program distinguish successful integer input from invalid input and report a diagnostic through std::cerr.
Takeaway: Use << for output, >> for formatted input, and std::getline for complete lines; check stream state when input may be invalid.
Putting the fundamentals together
A small complete program can combine the concepts in a predictable sequence:
Include the facilities it needs, such as
<iostream>and<string>.Enter through
main.Declare and initialize variables.
Read values with
orstd::getline.Evaluate expressions and assign results.
Write results with
.Return from
main.
For example, a program can declare std::string name; and int year{};, read a name with std::getline(, name), read a year with >> year, and calculate an approximate age with const int approximate_age = current_year - year;. It can then insert the name and result into output using .
At runtime, main normally executes statements in order unless a control-flow changes that order. Before runtime, the build process has already processed included headers, performed , and completed .
Takeaway: When debugging a beginner C++ program, trace both dimensions: how the build creates the executable and how main executes its statements.