SoFunction
Updated on 2025-04-06

Collection of usage of curly braces in C++

I have not summarized the use of curly braces in C++ since I learned C++, so I will record it in this article.

Method 1: Define code blocks

One of the most commonly used methods, without explanation:

if (condition) {
    // Code block} else {
    // Another code block}

Method 2: Scope control

Code like the following cannot be executed because the variable a variable is not scoped enough for cout to access.

    {
        int a = 10;
    }
    cout << a << endl;
    return 0;

Method 3: Definition of Class and Structure

This method is also very common and will not be explained much.

struct Point {
    int x;
    int y;
};

class Rectangle {
    int width, height;
public:
    Rectangle(int w, int h) : width(w), height(h) {}
    int area() { return width * height; }
};

Method 4: Initialize the list

Brace initialization (also known as unified initialization) was introduced in C++11, which can be used to initialize variables, arrays, containers, etc.

Simple variable initialization

    int x{10};
    double y{3.14};

Array initialization

    int arr[3] = {1, 2, 3};

Container initialization

    std::vector<int> vec = {1, 2, 3, 4};

Unified initialization method can avoid narrow conversion problems and improve code security.

It is worth mentioning that the famous cosmic construction expression is also the same principle.

Method 5: Constructor delegate

class Example {
    int a;
public:
    Example(int x) : a{x} {}
};

Method 6: Inline object definition

struct Point {
    int x, y;
};
Point p = {10, 20}; // Use braces to initialize directly

For anonymous or temporary objects, this writing is concise and clear.

Method 7: Function body of lambda expression

auto lambda = []() {
    return 42;
};

Method 8: Inline namespace

Braces are used to define the scope of a namespace.

namespace MyNamespace {
inline namespace v1 {
    void func() {}
}
}

All of this is the case at present, if you have new experiences, please continue to add them.

This is the end of this article about the collection of curly braces in C++. For more related contents of curly braces, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!