What is the purpose of anonymous { } blocks in C style languages (C, C++, C#)
Example -
void function()
{
{
int i = 0;
i = i + 1;
}
{
int k = 0;
k = k + 1;
}
}
Edit - Thanks for all of the excellent answers!
It limits the scope of variables to the block inside the { }.
Brackets designate an area of scope - anything declared within the brackets is invisible outside of them.
Furthermore, in C++ an object allocated on the stack (e.g. without the use of 'new') will be destructed when it goes out of scope.
In some cases it can also be a way to highlight a particular piece of a function that the author feels is worthy of attention for people looking at the source. Whether this is a good use or not is debatable, but I have seen it done.
They are often useful for RAII purposes, which means that a given resource will be released when the object goes out of scope. For example:
void function()
{
{
std::ofstream out( "file.txt" );
out << "some data\n";
}
// You can be sure that "out" is closed here
}
By creating a new scope they can be used to define local variables in a switch statement.
e.g.
switch (i)
{
case 0 :
int j = 0; // error!
break;
vs.
switch (i)
{
case 0 :
{
int j = 0; // ok!
}
break;
{ ... }
opens up a new scope
In C++, you can use them like this:
void function() {
// ...
{
// lock some mutex.
mutex_locker lock(m_mutex);
// ...
}
// ...
}
Once control goes out of the block, the mutex locker is destroyed. And in its destructor, it would automatically unlock the mutex that it's connected to. That's very often done, and is called RAII (resource acquisition is initialization) and also SBRM (scope bound resource management). Another common application is to allocate memory, and then in the destructor free that memory again.
Another purpose is to do several similar things:
void function() {
// set up timer A
{
int config = get_config(TIMER_A);
// ...
}
// set up timer B
{
int config = get_config(TIMER_B);
// ...
}
}
It will keep things separate so one can easily find out the different building blocks. You may use variables having the same name, like the code does above, because they are not visible outside their scope, thus they do not conflict with each other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With