Home Item 18 - Initialization in if Statements (English)
Post
Cancel

Item 18 - Initialization in if Statements (English)

Initialization in if Statements

As the title suggests, this section is relatively simple. C++17 introduced a new feature that allows for initialization within an if statement.

This means we can declare and initialize variables within the if statement, limiting their scope to the if statement itself.

This makes the code more concise and prevents variables from leaking into a broader scope.

Syntax

In C++17, the syntax for an if statement can be written in the following form:

1
2
3
4
5
6
if (init_statement; condition)
{
    // code block
}

Let’s look at a few examples to make this clearer:

File Opening Check

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <fstream>

int main() {
    if (std::ifstream file{"example.txt"}; file.is_open()) {
        std::cout << "File opened successfully." << '\n';
    } else {
        std::cout << "Failed to open the file." << '\n';
    }

    return 0;
}


Pointer Check

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main() {
    int x = 10;
    int* p = &x;

    if (int* ptr = p; ptr) {
        std::cout << "Pointer is valid and points to: " << *ptr << '\n';
    } else {
        std::cout << "Pointer is null." << '\n';
    }

    return 0;
}

Mathematical Calculation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main() {
    int a = 5;
    int b = 10;
    a++;

    if (int sum = a + b; sum > 10) {
        std::cout << "Sum is greater than 10: " << sum << '\n';
    } else {
        std::cout << "Sum is 10 or less: " << sum << '\n';
    }

    return 0;
}

Debugging with Breakpoints

Desktop View

Before Entering the if Scope At this point, the local variable sum is not yet initialized.

Desktop View

Desktop View

Inside the if Scope The local variable sum appears and is accessible within this scope.

Desktop View

Desktop View

Exiting the if Scope After leaving the if scope, the local variable sum disappears.

Desktop View

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍