1.4 Control Flow
“Control flow” refers to the “order of program execution”—by default, programs execute in a “top-to-bottom, left-to-right” manner; however, in practical applications, we need to “determine whether to execute a segment of code based on conditions” (branching) or “repeat a segment of code” (looping). This section introduces the two most basic control flow statements in C++:<span><span>if</span></span> (branching) and <span><span>for</span></span> (looping).
1.4.1 <span><span>if</span></span> Statement: Conditional Branching
<span><span>The </span></span>if<span><span> statement serves to "execute a segment of code if a certain condition is met; otherwise, execute another segment of code (optional)." </span></span>
Syntax Structure
// Single branch: execute if condition is trueif (condition_expression) { code_block1; // executed when condition is true}// Double branch: execute code_block1 if condition is true, otherwise execute code_block2if (condition_expression) { code_block1; // executed when condition is true} else { code_block2; // executed when condition is false}
- Condition expression: must be of “boolean type” (
<span><span>bool</span></span>)—<span><span>true</span></span>(true, non-zero values are treated as<span><span>true</span></span>) or<span><span>false</span></span>(false, 0 is treated as<span><span>false</span></span>). - Code block: if there is only one statement,
<span><span>{}</span></span>can be omitted; however, for clarity and to avoid errors in future modifications (such as mistakenly adding statements), it is recommended to always include<span><span>{}</span></span>regardless of the number of statements.
Example: Determine if a number is positive
#include<iostream>using namespace std;int main() { int num; cout << "Please enter an integer:"; cin >> num; if (num > 0) { // condition: num is greater than 0 cout << num << " is positive" << endl; } else if (num < 0) { // additional branch: num is less than 0 (else if can be multiple) cout << num << " is negative" << endl; } else { // remaining case: num equals 0 cout << num << " is zero" << endl; } return 0;}
1.4.2 <span><span>for</span></span> Statement: Looping
<span><span>The </span></span>for<span><span> statement serves to "repeat a segment of code until a termination condition is met"—especially suitable for scenarios with a "known number of iterations" (e.g., iterating through integers from 1 to 10).</span></span>
Syntax Structure
for (initialization_expression; condition_expression; update_expression) { loop_body; // executed when condition is true, updates expression after execution}
- Initialization expression: executed once before the loop starts, usually used to define and initialize the loop variable (e.g.,
<span><span>int i = 0</span></span>). - Condition expression: checked before each execution of the loop body—if it is
<span><span>true</span></span>, the loop body is executed; if it is<span><span>false</span></span>, the loop exits. - Update expression: executed after each execution of the loop body, usually used to update the loop variable (e.g.,
<span><span>i++</span></span>, which increments<span><span>i</span></span>by 1).
Example: Calculate the sum from 1 to 10
#include<iostream>using namespace std;int main() { int sum = 0; // store total sum, initial value is 0 // Loop: i from 1 to 10 (10 times total) for (int i = 1; i <= 10; ++i) { sum += i; // equivalent to sum = sum + i, adding i to sum each time } cout << "The sum from 1 to 10 is:" << sum << endl; // output result: 55 return 0;}
Scope of Loop Variable
- In the above code,
<span><span>int i = 1</span></span>is defined in the<span><span>for</span></span>“initialization expression”—according to the C++11 standard, the<span><span>i</span></span>variable’s scope is limited to the<span><span>for</span></span>loop body (after the loop ends,<span><span>i</span></span>can no longer be used), which is the recommended practice (to avoid variable pollution in the outer scope). - If
<span><span>i</span></span>is defined outside the<span><span>for</span></span>loop (e.g.,<span><span>int i; for (i = 1; ...)</span></span>), then the<span><span>i</span></span>variable’s scope extends beyond the<span><span>for</span></span>loop, which is not recommended.
1.5 Introduction to Classes
C++ is an “object-oriented programming language,” and “classes” are the core of object orientation—the role of a class is to “encapsulate data (attributes) and functions (methods) that operate on the data,” forming a “custom type.” This section does not delve into the implementation of classes but rather introduces readers to “how to use classes” through the <span><span>Sales_item</span></span> class from the C++ standard library, with detailed explanations of class definitions and encapsulation in subsequent chapters.
1.5.1 <span><span>Sales_item</span></span> Class Functionality
<span><span>Sales_item</span></span> is a “class for handling book sales data,” encapsulating the following information (data) and operations (methods):
- Data: ISBN number of the book (unique identifier for a book), sales quantity, unit price, total sales amount.
- Methods:
- Read sales records (from
<span><span>cin</span></span>). - Output sales records (to
<span><span>cout</span></span>). - Accumulate sales records (adding the sales quantity and total sales amount of two books with the same ISBN).
1.5.2 Prerequisites for Using <span><span>Sales_item</span></span> Class
To use the <span><span>Sales_item</span></span> class, two conditions must be met:
- Include the header file:
<span><span>#include</span><span> "Sales_item.h"</span></span>—note that double quotes are used here<span><span>""</span></span>, not angle brackets<span><span><></span></span><code><span><span>:</span></span>
- Angle brackets
<span><span><></span></span>: used to include standard library header files (e.g.,<span><span><iostream></span></span>), the compiler will look in the “system standard library directory”. - Double quotes
<span><span>""</span></span>: used to include custom header files (e.g.,<span><span>Sales_item.h</span></span><code><span><span>, usually written by yourself or third-party library header files), the compiler will first look in the "directory of the current source file" and if not found, will then look in the system standard library directory.</span></span>
<span><span>Sales_item.h</span></span> file: this file is not a default file in the C++ standard library and needs to be downloaded from the official website of “C++ Primer” (or accompanying resources) and placed in the same directory as the source file.1.5.3 Example: Using <span><span>Sales_item</span></span> to Process Sales Data
#include<iostream>#include"Sales_item.h" // include the header file for Sales_item classusing namespace std;int main() { Sales_item book1, book2; // define two variables of Sales_item type (similar to int a;) // read sales records for two books with the same ISBN cout << "Please enter the sales record for the first book (ISBN quantity unit price):"; cin >> book1; // call the input method of Sales_item cout << "Please enter the sales record for the second book (ISBN quantity unit price):"; cin >> book2; // check if the ISBNs of the two books are the same (the == operator is overloaded by Sales_item) if (book1.isbn() == book2.isbn()) { Sales_item total = book1 + book2; // accumulate sales records (+ operator is overloaded) cout << "Total sales record for the two books:" << total << endl; // output total record return 0; } else { cerr << "The ISBNs of the two books are different, cannot accumulate!" << endl; // cerr: standard error stream return -1; // return non-zero value, indicating abnormal program termination }}
Key Concept: Operator Overloading
- In the above code,
<span><span>cin >> book1</span></span>,<span><span>book1 + book2</span></span>,<span><span>book1.isbn() == book2.isbn()</span></span>and other operations appear to be “using standard operators on class objects”—this is the C++ feature of “operator overloading”: classes can customize the behavior of<span><span>>></span></span>,<span><span>+</span></span>,<span><span>==</span></span>and other operators, making object manipulation more intuitive (just like manipulating<span><span>int</span></span>,<span><span>double</span></span>and other basic types). <span><span>cerr</span></span>: is the “standard error stream,” and the difference from<span><span>cout</span></span><span><span> is:</span></span><code><span><span>cerr</span></span>is unbuffered, error messages are displayed immediately; while<span><span>cout</span></span><span><span> is buffered, which may delay display—usually, </span></span><code><span><span>cerr</span></span><span><span> is used to output error messages.</span></span>