Statements and Control Structures
COS2614 - Programming: Contemporary Concepts · C++ Language Reference
Statements and Control Structures
This topic covers statements and control structures in C++. These are essential for controlling the flow of execution in your programs. Understanding how to use these structures allows you to create more complex and functional applications.
Key idea: After studying this topic, you should be able to:
- Identify different types of statements in C++.
- Use control structures to manage the flow of your program.
- Implement conditionals and loops effectively.
Types of Statements
In C++, statements are instructions that the compiler executes. They can be categorized into several types:
1. Expression Statements
An expression statement consists of an expression followed by a semicolon. For example:
int x = 5;This statement declares a variable x and initializes it with the value 5.
2. Compound Statements
A compound statement groups multiple statements into a single block, enclosed in curly braces:
if (x > 0) {
cout << "Positive";
}3. Control Flow Statements
Control flow statements change the execution order of statements. These include:
- Conditional statements (if, else)
- Looping statements (for, while)
- Jump statements (break, continue)
Control Structures
Control structures allow you to control the flow of your program based on conditions.
1. Conditional Statements
Conditional statements execute different code blocks based on a condition. The most common are if and else.
if (x > 10) {
cout << "x is greater than 10";
} else {
cout << "x is 10 or less";
}2. Loops
Loops allow you to execute a block of code multiple times. Common loop types are:
a. For Loop
for (int i = 0; i < 5; i++) {
cout << i;
}This loop will print the numbers 0 to 4.
b. While Loop
int j = 0;
while (j < 5) {
cout << j;
j++;
}This loop will also print the numbers 0 to 4.
Type Casting
C++ allows type casting to convert one data type to another. You can use static_cast and const_cast for this purpose.
Example of Type Casting
double m2k = 1.609;
int miles = 23;
double kilometers = miles * m2k;
cout << static_cast(kilometers); // Outputs 37In this example, static_cast converts kilometers from double to int.
Watch out: Be careful when using const_cast to change const objects. This can lead to undefined behaviour if the object is stored in read-only memory.
Summary
- Statements are instructions executed by the compiler.
- Control structures manage the flow of execution.
- Conditional statements allow branching based on conditions.
- Loops enable repeated execution of code blocks.
- Type casting is used to convert data types.
Check your understanding
- What is the difference between a statement and a control structure?
- Write an example of a for loop that counts from 1 to 10.
- Explain the purpose of
static_castin C++. - What could happen if you attempt to modify a const object using
const_cast?