1 C++ Foundations and Syntax

A practical introduction to C++ program structure, translation stages, syntax, names, values, expressions, console input and output, and readable coding conventions.

Program structure and entry point

A C++ program is organized into one or more source files, commonly using the .cpp extension. These files contain declarations and definitions for functions, variables, types, and other program entities.

A minimal program has this shape:

#include <iostream>

int () {

<< "Hello, C++!\\n";

return 0;

}

The important parts are:

  • #include <iostream> requests declarations for standard input and output facilities.

  • int () defines the program's starting function.

  • { ... } encloses the function body.

  • << ... sends data to standard output.

  • return 0; ends and conventionally reports successful execution.

  • ; terminates most declarations and statements.

C++ is case-sensitive, so , , and are different names.

Takeaway: Read a small C++ program from the outside in: identify included facilities, locate , inspect its braces, and then follow the statements inside.

From source code to execution

A C++ program passes through several conceptual stages before it runs:

  1. handles directives such as #include and prepares the source text.

  2. checks syntax and meaning and translates each source file into object-file information related to machine code.

  3. combines object files and required libraries and resolves references between them.

  4. Execution begins when the operating system loads the executable and calls .

For example, a Microsoft Visual C++ command can compile and link a simple file: cl /EHsc hello.cpp. Toolchain commands differ, but the general distinction is important: checks and translates source code, while constructs the final executable from program components.

Different failure stages suggest different causes:

  • A syntax error, such as a missing , prevents .

  • A linker error occurs after successful when a required definition cannot be found.

  • A run-time error occurs while the executable is running.

Takeaway: When diagnosing a problem, first ask whether it occurs during , , or execution.

Comments and documentation

Comments document code and are ignored during translation. They should explain intent, assumptions, or non-obvious decisions rather than merely repeat what the code already says.

A single-line comment begins with // and continues to the end of the line. For example: int count = 10; // Number of items.

A block comment begins with /* and ends with */; it can span multiple lines.

Comments are treated as whitespace during translation. Therefore, they do not produce executable behavior and cannot be used to separate tokens in arbitrary ways.

Takeaway: Use comments to preserve the reasoning behind code, especially when the purpose or assumption is not obvious from the syntax alone.

Keywords and identifiers

C++ distinguishes between reserved language words and names chosen by the programmer. A has special meaning and normally cannot name a variable, function, or class. Examples include int, if, return, class, public, const, true, false, and nullptr.

An is a programmer-defined name, such as a variable, function, or class name. Examples include int itemCount; and double average_score;.

Identifiers may contain letters, digits, and underscores, but they cannot begin with a digit, cannot be keywords, and are case-sensitive. Valid examples include total, item2, and student_name. Invalid examples include 2items, total-cost, and return.

Names beginning with an underscore followed by an uppercase letter, and many names beginning with a double underscore, are reserved for the implementation. Avoid those patterns in ordinary programs. Prefer descriptive names such as numberOfStudents or total_cost when they communicate meaning better than short names such as n or x.

Takeaway: Choose names that are legal, descriptive, consistently styled, and unlikely to conflict with language or implementation-reserved names.

Literals and values

A is a value written directly in source code. Common categories include:

  • Integer literals: 0, 42, -7, and 0xFF.

  • Floating-point literals: 3.14 and 2.0e3.

  • Character literals: 'A' and '\\n'.

  • String literals: "C++" and "Line 1\\n".

  • Boolean literals: true and false.

  • The null pointer : nullptr.

A character uses single quotes, while a string uses double quotes. For example: char initial = 'A'; and const char* message = "Hello";.

Escape sequences represent special characters inside character and string literals. For example, '\\n' represents a newline, '\\t' represents a tab, and '\\\\' represents a backslash. A numeric suffix can influence a 's type, such as 42L or 3.14F.

Takeaway: Look at both the spelling and the delimiters of a : quotes distinguish characters from strings, prefixes can indicate notation, and suffixes can influence numeric type.

Operators and expressions

An combines literals, names, function calls, and operators to produce a value or side effect. Common operator groups include:

  • Arithmetic: +, -, *, /, and %.

  • Assignment: =, +=, -=, *=, and /=.

  • Comparison: ==, !=, <, >, <=, and >=.

  • Logical: &&, ||, and !.

  • Increment and decrement: ++ and --.

  • Conditional selection: ?:.

  • Scope resolution: ::.

  • Function calls: ().

For example, int width = 4;, int height = 5;, int area = width * height;, and bool large = area > 10; use expressions to initialize values and compare results.

Operators have precedence and associativity rules that determine grouping. Multiplication and division generally bind more tightly than addition and subtraction. Thus, 2 + 3 * 4 produces 14, while (2 + 3) * 4 produces 20.

Use parentheses when the intended order matters. Also distinguish assignment from equality testing: x = 5; assigns a value, whereas x == 5; tests whether two values are equal. An can serve as a statement when followed by a , as in x = x + 1;.

Takeaway: Identify each operator's purpose, do not confuse = with ==, and use parentheses to make important grouping explicit.

Console input and output

The <iostream> header provides stream-based console input and output. The most common stream objects at this level are:

  • for standard output.

  • for standard input.

  • std::cerr for standard error output.

The std:: prefix identifies names from the standard library's std namespace.

Use the insertion operator << with to send values to an output stream. For example, int apples = 3; followed by << "Apples: " << apples << '\\n'; displays a label, a value, and a newline. Several values can be chained.

\\n inserts a newline. std::endl also inserts a newline and flushes the stream, whereas \\n is often sufficient for ordinary output.

Use the extraction operator >> with to read formatted values. For example, int age{}; followed by >> age; attempts to read an integer into age.

The destination type influences interpretation. Reading into an integer expects numeric input, while reading into a string-like word extracts one whitespace-delimited word. Formatted input can set stream error states when the entered value does not match the expected type.

Takeaway: Use << to send formatted values to an output stream and >> to extract formatted values from an input stream.

Syntax and readability conventions

Consistent formatting makes program structure easier to see and reduces mistakes. Use braces to show the boundaries of functions, classes, and control structures, and indent their contents consistently.

Although braces can be optional for a single controlled statement, using them consistently makes later changes safer. A typical structure places an opening brace after the associated declaration and indents the statements inside it.

A usually ends a declaration or statement, such as int count = 0; or count = count + 1;.

A function definition does not place a after its closing brace. A class definition normally does require one, as in class Sensor { };.

Whitespace generally separates tokens and improves presentation. A common convention uses four spaces per indentation level and places the opening brace on the same line as the associated declaration.

Prefer initializing objects when they are created, for example int count{0};, double temperature{21.5};, and bool complete{false};. Keep names within a limited, meaningful scope and group related code so that the program's structure is easy to follow.

Takeaway: Formatting is not merely cosmetic: braces, semicolons, indentation, initialization, and scope conventions help communicate how code is organized.