I
I
IliaNeverov2021-06-24 15:35:24
C++ / C#
IliaNeverov, 2021-06-24 15:35:24

What does just { code block here } mean in c++?

What do they simply mean

{
//блок кода
 }

without a name, arguments or something like that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tugo, 2021-06-24
@IliaNeverov

The properties of the code block are used:
1. a new scope is created
2. the object created inside the code block will be deleted upon completion (that is, the destructor will be called). In combination with RAII is sometimes convenient.

// Когда не хочется придумывать новое имя другой переменной, которая точно такая же по смыслу.
// И хочется дать ей константность - ее менять я не собираюсь, в смысле изменчивости переменной.
const bool ok = foo1();
if (!ok)
    return;
{
    const bool ok = foo2();
    if (!ok)
        return;
}

// Когда надо защитить мьютексом изменение переменной, на как можно более короткое время.
...  некий код
{
    const std::lock_guard<std::mutex> lock(_mutex);
    ++i;
    // _mutex is automatically released when lock goes out of scope
}
... продолжаем код

Or measure the execution time of a piece of code. We create an object, in the constructor of which we capture the current time, in the destructor we display the elapsed time in the log.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question