Topic 16 of 91 3. Control Flow in C++ Interactive Tutorial

C++ Statements: Declarations, Expressions, Compound Blocks, and More

12 mins read Last updated: 26 Sep 2026 17,500 views

Direct Answer & Core Concept

Every C++ program is made up of instructions that tell the computer what to do. These instructions are called statements.

For example, when you create a variable, calculate two numbers, display a message, or repeat an operation using a loop, you are writing statements in C++.

Statements are the basic building blocks of a C++ program. They help you organize instructions, make decisions, control program execution, and perform different tasks.

But what exactly is a statement in C++? What is the difference between a declaration statement, an expression statement, and a compound statement?

Detailed Explanation & Mechanics

What Is a Statement in C++?

A statement in C++ is a complete instruction that tells the compiler to perform a particular action.

Statements can declare variables, assign values, perform calculations, execute functions, control loops, or make decisions.

Consider this example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int age = 25;

    cout << "My age is: " << age;

    return 0;
}

Output:

In this program:

  • int age = 25; is a declaration statement.

  • cout << "My age is: " << age; is an expression statement.

  • return 0; is a jump statement.

  • The instructions inside main() form a compound statement.

Each statement performs a specific task and helps the program execute correctly.

Main Types of Statements in C++

C++ provides several types of statements. Each type has a different purpose in a program.

The main categories are:

  1. Declaration statements

  2. Expression statements

  3. Compound statements (blocks)

  4. Selection statements

  5. Iteration statements

  6. Jump statements

  7. Labeled statements

  8. Try-blocks

Let's understand each type with simple explanations and practical examples.

1. Declaration Statements in C++

A declaration statement is used to introduce a variable, function, or other entity into a program.

It tells the compiler the name and type of an entity so that it can be used in the appropriate scope.

Variables are commonly declared using data types such as int, float, double, char, and bool.

Syntax

You can also declare and initialize a variable in the same statement.

main.cpp
Run Online
data_type variable_name = value;

Example: Variable Declaration

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int age = 25;
    float marks = 85.5;
    char grade = 'A';
    double salary = 35000.75;

    cout << "Age: " << age << endl;
    cout << "Marks: " << marks << endl;
    cout << "Grade: " << grade << endl;
    cout << "Salary: " << salary << endl;

    return 0;
}

Output:

main.cpp
Run Online
Age: 25
Marks: 85.5
Grade: A
Salary: 35000.75

Explanation

In this example:

  • int age = 25; declares an integer variable.

  • float marks = 85.5; declares a floating-point variable.

  • char grade = 'A'; declares a character variable.

  • double salary = 35000.75; declares a double-precision variable.

All four lines are declaration statements.

Example: Multiple Variable Declarations

You can declare multiple variables of the same type in a single declaration.

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int a = 10, b = 20, c = 30;

    cout << a + b + c;

    return 0;
}

Output:

Where Are Declaration Statements Used?

Declaration statements are used when:

  • Creating variables.

  • Defining constants.

  • Declaring references.

  • Declaring pointers.

  • Introducing objects of classes.

  • Defining local variables inside functions and blocks.

2. Expression Statements in C++

An expression statement is a statement formed from an expression followed by a semicolon.

Expressions can perform calculations, assign values, call functions, or modify variables.

Syntax

Example: Assignment Expression Statement

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int number;

    number = 100;

    cout << "Number: " << number;

    return 0;
}

Output:

Here, number = 100; is an expression statement because it assigns a value to the variable.

Example: Arithmetic Expression Statement

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int a = 10;
    int b = 20;

    int result = a + b;

    cout << "Sum: " << result;

    return 0;
}

Output:

The calculation a + b is an expression used within a declaration statement.

Example: Function Call Expression Statement

main.cpp
Run Online
#include <iostream>
using namespace std;

void display() {

    cout << "Welcome to C++!";
}

int main() {

    display();

    return 0;
}

Output:

The statement display(); is an expression statement because it calls a function.

Important: Null Statement

A semicolon by itself is called a null statement.

It performs no operation. It can be useful in situations where the syntax requires a statement but no action is needed.

However, an accidental extra semicolon after a condition or loop can cause unexpected behaviour.

3. Compound Statements in C++ (Blocks)

A compound statement is a group of statements enclosed within curly braces { }.

It is also called a block statement.

Compound statements allow you to combine multiple instructions into a single statement.

They are commonly used with functions, loops, conditional statements, and other control structures.

Syntax

main.cpp
Run Online
{
    statement1;
    statement2;
    statement3;
}

Example: Compound Statement

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    {
        int a = 10;
        int b = 20;

        int sum = a + b;

        cout << "Sum: " << sum << endl;
    }

    return 0;
}

Output:

Explanation

In this example:

  • The opening curly brace { starts a block.

  • The variables a and b are declared inside the block.

  • The calculation is performed inside the same block.

  • The closing curly brace } ends the block.

The variables declared inside the block are local to that block and cannot normally be accessed outside it.

Example: Multiple Statements Inside a Block

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int number = 10;

    if (number > 0) {

        cout << "Positive Number" << endl;

        number = number + 5;

        cout << "Updated Number: " << number << endl;
    }

    return 0;
}

Output:

main.cpp
Run Online
Positive Number
Updated Number: 15

The statements inside the if block are executed together when the condition is true.

Benefits of Compound Statements

  • Group multiple instructions together.

  • Organize program logic.

  • Control variable scope.

  • Make conditional statements and loops easier to write.

  • Improve code readability.

4. Selection Statements in C++

Selection statements allow a program to make decisions based on conditions.

They determine which block of code should execute depending on whether a condition is true or false.

C++ provides the following main selection statements:

  1. if

  2. if-else

  3. else-if ladder

  4. Nested if

  5. switch

A. if Statement

The if statement executes a block of code when a specified condition is true.

Syntax:

main.cpp
Run Online
if (condition) {
    // Code executes when condition is true
}

Example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int age = 20;

    if (age >= 18) {

        cout << "You are eligible to vote.";
    }

    return 0;
}

Output:

The condition age >= 18 is true, so the program executes the code inside the if block.

B. if-else Statement

The if-else statement provides two possible execution paths.

If the condition is true, the if block runs. Otherwise, the else block runs.

Syntax:

main.cpp
Run Online
if (condition) {
    // True condition
} else {
    // False condition
}

Example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int number = 7;

    if (number % 2 == 0) {

        cout << "Even Number";

    } else {

        cout << "Odd Number";
    }

    return 0;
}

Output:

C. else-if Ladder

An else-if ladder is used when you need to check multiple conditions.

Example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int marks = 85;

    if (marks >= 90) {

        cout << "Grade A+";

    } else if (marks >= 80) {

        cout << "Grade A";

    } else if (marks >= 70) {

        cout << "Grade B";

    } else {

        cout << "Grade C";
    }

    return 0;
}

Output:

The program checks each condition in order and executes the first matching block.

D. Nested if Statement

A nested if statement means placing one if statement inside another if statement.

Example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int age = 25;
    bool hasLicense = true;

    if (age >= 18) {

        if (hasLicense) {

            cout << "You can drive.";

        } else {

            cout << "You need a driving license.";
        }

    } else {

        cout << "You are not old enough to drive.";
    }

    return 0;
}

Output:

E. switch Statement

The switch statement is used when you want to select one option from several possible values.

It commonly works with integral types, enumeration types, and certain other types convertible to an integral or enumeration type.

Syntax:

main.cpp
Run Online
switch (expression) {

    case value1:
        // Code
        break;

    case value2:
        // Code
        break;

    default:
        // Default code
}

Example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int day = 3;

    switch (day) {

        case 1:
            cout << "Monday";
            break;

        case 2:
            cout << "Tuesday";
            break;

        case 3:
            cout << "Wednesday";
            break;

        default:
            cout << "Invalid Day";
    }

    return 0;
}

Output:

The break statement prevents execution from continuing into the next case.

Where Are Selection Statements Used?

  • Checking user eligibility.

  • Calculating grades.

  • Validating user input.

  • Creating menu-driven applications.

  • Handling different program conditions.

  • Selecting operations in calculators.

5. Iteration Statements in C++ (Loops)

Iteration statements are used to repeat a block of code multiple times.

They are also called looping statements.

C++ provides three main types of loops:

  1. for loop

  2. while loop

  3. do-while loop

These loops help reduce repeated code and make programs more efficient.

A. for Loop

A for loop is commonly used when you know how many times you want to repeat an operation.

Syntax:

main.cpp
Run Online
for (initialization; condition; update) {

    // Code to repeat
}

Example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    for (int i = 1; i <= 5; i++) {

        cout << i << endl;
    }

    return 0;
}

Output:

Explanation

  • Initialization sets the starting value.

  • Condition determines whether the loop should continue.

  • Update changes the variable after each iteration.

B. while Loop

A while loop executes a block of code as long as its condition remains true.

Syntax:

main.cpp
Run Online
while (condition) {

    // Code to repeat
}

Example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int i = 1;

    while (i <= 5) {

        cout << i << endl;

        i++;
    }

    return 0;
}

Output:

The condition is checked before each iteration. If it is false initially, the loop body will not execute.

C. do-while Loop

A do-while loop executes the code block first and checks the condition afterward.

This means the loop body executes at least once.

Syntax:

main.cpp
Run Online
do {

    // Code to repeat

} while (condition);

Example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int i = 1;

    do {

        cout << i << endl;

        i++;

    } while (i <= 5);

    return 0;
}

Output:

Difference Between for, while, and do-while Loops

Featureforwhiledo-while
Condition checkingBefore executionBefore executionAfter execution
Minimum executionsZeroZeroOne
Best useKnown iteration countCondition-based repetitionAt least one execution required
SyntaxInitialization, condition, updateConditionCode followed by condition

6. Jump Statements in C++

Jump statements change the normal flow of program execution.

They are used to exit loops, skip iterations, return from functions, or transfer control to another location.

C++ provides several jump statements:

  1. break

  2. continue

  3. return

  4. goto

A. break Statement

The break statement immediately terminates the nearest enclosing loop or switch statement.

Example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    for (int i = 1; i <= 10; i++) {

        if (i == 5) {
            break;
        }

        cout << i << endl;
    }

    return 0;
}

Output:

When i becomes 5, the break statement terminates the loop.

B. continue Statement

The continue statement skips the remaining statements in the current loop iteration and moves to the next iteration.

Example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    for (int i = 1; i <= 5; i++) {

        if (i == 3) {
            continue;
        }

        cout << i << endl;
    }

    return 0;
}

Output:

The number 3 is skipped because the continue statement moves execution to the next iteration.

C. return Statement

The return statement ends the execution of a function and can send a value back to the calling function.

Example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int add(int a, int b) {

    return a + b;
}

int main() {

    int result = add(10, 20);

    cout << "Sum: " << result;

    return 0;
}

Output:

The return a + b; statement sends the calculated result back to main().

D. goto Statement

The goto statement transfers program execution to a labeled statement within the same function.

Example:

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int number = 1;

    if (number == 1) {
        goto message;
    }

    cout << "This line is skipped.";

    message:

    cout << "Welcome to C++!";

    return 0;
}

Output:

The goto statement transfers control directly to the message label.

Important: Although goto is supported in C++, it should generally be avoided in ordinary programming because it can make code difficult to understand. Loops, functions, and conditional statements are usually better choices.

7. Labeled Statements in C++

A labeled statement is a statement that has a label attached to it.

Labels are mainly used with goto and case or default labels in a switch statement.

Types of Labels

  • Identifier labels

  • case labels

  • default labels

Example: Identifier Label

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int number = 10;

    start:

    cout << "Number: " << number;

    return 0;
}

Output:

Here, start: is an identifier label.

It marks a location in the function that can be targeted by a goto statement.

Example: Case and Default Labels

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int choice = 2;

    switch (choice) {

        case 1:
            cout << "Option One";
            break;

        case 2:
            cout << "Option Two";
            break;

        default:
            cout << "Invalid Option";
    }

    return 0;
}

Output:

The case and default labels identify the different execution paths inside the switch statement.

8. Try-Blocks in C++

A try-block is used for exception handling in C++.

It allows you to execute code that might generate an exception and handle the problem using a catch block.

Try-blocks help prevent certain errors from unexpectedly terminating program execution.

Syntax

main.cpp
Run Online
try {

    // Code that may throw an exception

} catch (exception_type e) {

    // Handle the exception
}

Example: Using try and catch

main.cpp
Run Online
#include <iostream>
#include <stdexcept>
using namespace std;

int main() {

    int age = -5;

    try {

        if (age < 0) {

            throw invalid_argument("Age cannot be negative.");
        }

        cout << "Age: " << age;

    } catch (const invalid_argument& e) {

        cerr << "Error: " << e.what();
    }

    return 0;
}

Output:

main.cpp
Run Online
Error: Age cannot be negative.

Explanation

  • The try block contains code that may throw an exception.

  • The throw statement raises an exception when the condition is invalid.

  • The catch block handles the exception.

  • e.what() provides the error message.

Try-blocks are especially useful when working with file operations, input validation, and applications that need structured error handling.

Difference Between Statements and Expressions in C++

Statements and expressions are related, but they are not the same.

An expression produces a value or performs an operation. A statement is a complete instruction that performs an action.

FeatureExpressionStatement
MeaningRepresents a calculation or operationComplete instruction
Main purposeProduces a value or effectPerforms a program action
Examplea + ba = b;
SemicolonDepends on where it is usedMany simple statements end with one
UsageUsed inside statements and other expressionsForms the structure of a program

Example

main.cpp
Run Online
int a = 10;
int b = 20;

a + b;

Here:

  • a + b is an expression.

  • a + b; is an expression statement.

  • int a = 10; is a declaration statement.

Understanding this difference helps you read and write C++ code more effectively.

Semicolons and Curly Braces in C++

Two important symbols used when writing C++ statements are semicolons and curly braces.

1. Semicolon (;)

A semicolon marks the end of many simple statements.

Example:

main.cpp
Run Online
int age = 25;
cout << age;
return 0;

2. Curly Braces { }

Curly braces define a compound statement or block.

Example:

main.cpp
Run Online
if (age >= 18) {

    cout << "Adult";

}

The statements inside the braces belong to the if block.

Important: Not every C++ statement ends with a semicolon directly. For example, an if, for, or while statement followed by a compound block does not require a semicolon after the closing brace.

Complete C++ Program Using Different Statements

Let's combine declaration, expression, selection, iteration, compound, and jump statements in one program.

C++ Code

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    // Declaration statement
    int number = 5;
    int sum = 0;

    // Compound statement
    {
        cout << "Starting Number: " << number << endl;
    }

    // Iteration statement
    for (int i = 1; i <= number; i++) {

        // Selection statement
        if (i == 3) {
            continue;
        }

        // Expression statement
        sum += i;
    }

    // Output statement
    cout << "Total Sum: " << sum << endl;

    // Jump statement
    return 0;
}

Output

main.cpp
Run Online
Starting Number: 5
Total Sum: 12

Explanation

This program demonstrates several types of C++ statements:

  1. Declaration statements create the variables number and sum.

  2. A compound statement groups instructions inside curly braces.

  3. A for statement repeats the calculation.

  4. An if statement checks whether the current number is 3.

  5. A continue statement skips that iteration.

  6. An expression statement updates the sum.

  7. The return statement ends the main() function.

This example shows how different statements work together in a single C++ program.

Common Mistakes When Using Statements in C++

Beginners sometimes make mistakes while writing C++ statements. Understanding these mistakes will help you write cleaner programs.

1. Forgetting the Semicolon

Incorrect:

Correct:

Most simple statements require a semicolon at the end.

2. Missing Curly Braces

Incorrect:

main.cpp
Run Online
if (age >= 18)
    cout << "Adult";
    cout << "Eligible";

Only the first output statement belongs to the if condition.

Correct:

main.cpp
Run Online
if (age >= 18) {

    cout << "Adult";
    cout << "Eligible";

}

Use braces to group multiple instructions when they should execute together.

3. Confusing Assignment and Comparison

Incorrect:

main.cpp
Run Online
if (number = 10) {
    cout << "Ten";
}

Correct:

main.cpp
Run Online
if (number == 10) {
    cout << "Ten";
}

Use == when comparing values and = when assigning values.

4. Creating an Infinite Loop

Incorrect:

main.cpp
Run Online
int i = 1;

while (i <= 5) {

    cout << i;
}

The variable i is never updated, so the condition remains true.

Correct:

main.cpp
Run Online
int i = 1;

while (i <= 5) {

    cout << i << endl;

    i++;
}

5. Using break Outside a Loop or switch

The break statement is used to exit the nearest enclosing loop or switch statement. It cannot be used freely inside an ordinary function or block.

6. Declaring Variables in the Wrong Scope

A variable declared inside a compound block is generally available only within that block and its nested scopes.

Example:

main.cpp
Run Online
{
    int number = 10;
}

// number cannot be accessed here

Always declare variables in the scope where they are needed.

Best Practices for Writing C++ Statements

Follow these simple practices when writing C++ programs:

  • Use meaningful variable names.

  • End simple statements with semicolons.

  • Use curly braces to organize compound blocks.

  • Keep indentation consistent.

  • Use selection statements for decision-making.

  • Choose the correct loop for repeated operations.

  • Avoid unnecessary goto statements.

  • Check conditions carefully before using loops.

  • Keep statements short and readable.

  • Use exception handling when appropriate.

  • Declare variables close to where they are needed.

Frequently Asked Questions About C++ Statements

1. What is a statement in C++?

A statement is a complete instruction that tells a C++ program to perform a specific action, such as declaring a variable, calculating a value, or controlling program execution.

2. What are the main types of statements in C++?

The main statement categories include declaration, expression, compound, selection, iteration, jump, labeled, and try-block statements.

3. What is a declaration statement in C++?

A declaration statement introduces a variable, object, or other entity into a program. For example, int age = 25; declares and initializes an integer variable.

4. What is an expression statement in C++?

An expression statement is an expression followed by a semicolon. Examples include a = 10;, a++;, and display();.

5. What is a compound statement in C++?

A compound statement is a group of statements enclosed within curly braces { }. It is also called a block.

6. What are selection statements in C++?

Selection statements allow a program to make decisions. The main examples are if, if-else, and switch.

7. What are iteration statements in C++?

Iteration statements are used to repeat code. C++ provides for, while, and do-while loops.

8. What are jump statements in C++?

Jump statements change the normal flow of execution. Common examples are break, continue, return, and goto.

9. What is the difference between a statement and an expression?

An expression represents a calculation or operation that produces a value or effect. A statement is a complete instruction that performs an action.

10. Why are semicolons used in C++?

Semicolons mark the end of many simple C++ statements, including declarations, expression statements, and return statements.

11. What are curly braces used for in C++?

Curly braces { } define compound statements or blocks. They group multiple statements and establish a scope for local variables.

12. What is a null statement in C++?

A null statement is a single semicolon (;). It represents an empty statement that performs no operation.

13. What is the purpose of the return statement?

The return statement ends the execution of a function. It can also return a value to the calling function.

14. What is the purpose of a try-block in C++?

A try-block contains code that may throw an exception. A corresponding catch-block handles the exception when one is thrown.

Runnable Code Example: C++ Statements

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <vector>

int computeScore() { return 85; }

int main() {
    // C++17 if statement with initializer
    if (int score = computeScore(); score >= 80) {
        std::cout << "High performance score achieved: " << score << "
";
    } else {
        std::cout << "Score below threshold: " << score << "
";
    }
    // 'score' is automatically out of scope here

    // Compound Block Scope
    {
        std::vector<int> tempBuffer = {1, 2, 3};
        std::cout << "Buffer active with " << tempBuffer.size() << " elements
";
    } // tempBuffer memory automatically released here

    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What is the benefit of the C++17 "if with initializer" syntax?

A: It restricts the scope of helper variables strictly to the `if` and `else` branches, preventing variable leakage into the enclosing function and eliminating name collisions.
Q

Q: How does a compound block {} affect object lifetimes?

A: Any automatic (stack) variables declared inside `{}` are constructed when declared and guaranteed to have their destructors executed when the closing brace `}` is reached.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Use C++17 if (init; condition) to keep variable scopes minimal.
2. Enclose temporary work in compound {} blocks to trigger early RAII resource deallocation.
3. Avoid empty statement semicolons (;) that can cause unintended logic bugs.