Overview
In this chapter, we will delve into the heart of C++ programs: statements and their structure. We will explore how to write and organize code to create meaningful and efficient applications.
Statements: The Building Blocks
A C++ program is constructed from a series of statements. A statement is the smallest standalone unit in a program that performs some action or task.
Most (but not all) statements in C++ end in a semicolon ;
. If you see a line that ends in a semicolon, it's probably a statement.
It can be classified into several categories, here are some common types:
Declaration Statements
Declaration statements are used to define variables. Variables are essential for storing data in a program. In C++, you must declare a variable before using it. For example:
int age; // Declares an integer variable named 'age'.
Assignment Statements
Assignment statements assign values to variables. They use the assignment operator =
to store a value in a variable. For instance:
age = 30; // Assigns the value 30 to the 'age' variable.
Expression Statements
Expression statements consist of expressions that can be evaluated. An expression is a combination of variables, values, and operators that yield the result. For example:
int result = age * 10 + 7; // An expression that calculates a result.
Control Flow Statements
Control flow statements direct the flow of program execution. They include:
Conditional Statements (if, else, switch): These allow you to make decisions in your program based on certain conditions.
if (age >= 18) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false.
}
Looping Statements (for, while, do-while): These enable you to repeat a block of code multiple times.
for (int i = 0; i < 4; ++i){
// Code to repeat four times.
}
Jump Statements (break, continue, return): these provide mechanism for changing the program's flow.
Function Calls
Function calls are a type of statement that invoke predefined or user-defined functions. Functions are blocks of reusable code that perform special tasks. A function is a collection of statements that get executed sequentially (in order, from top to bottom) For example:
int sum = add(1, 7); // Calls a user-defined 'add' function.