So I have inherited some code that contains some odd stuff I've never seen before. I haven't been able to find any references to this code nor have I been able to determine if it does ANYTHING.
Here is a sample of it. I can't post the actual code, but hopefully my adaptation of it will be sufficient for someone to illuminate me.
...
for(i=0; i != 10; ++i)
{
if(SOME_TEST)
{
if(val == 0)
{
UPDATE_STUFF
}
continue;
}
// WEIRD CODE JUST BELOW THIS COMMENT
{
if(SOME_OTHER_TEST)
{
UPDATE_OTHER_STUFF
break;
}
};
// MOAR WEIRD CODEZ
{
if(A_THIRD_TEST)
{
UPDATE_DIFFENT_STUFF
continue;
}
};
// LAST BIT OF GOOFY STUFF
{
if(TEST_FOUR)
{
UPDATE_STILL_OTHER_THINGS
break;
}
};
}
...
I am very confuzzled by those seemingly random and useless { }; around those other portions of code. As I said, I have never seen this and haven't been able to figure out what difference it makes or find any references to similar code.
You can use {} by themselves to create an arbitrary scope. In this case, they are wrapping an if statement, which has its own scope already, so they seem useless to me. I don't think you even need the semicolon at the end of them either.
I admit that from the look of your pasted code that what I've written below may not be pertinent to you in this case.
However, you'll often see braces in code to create scope. The reason for creating scope is that automatic (stack allocated) variables created within this scope will be deallocated once they leave the scope.
A common usage of this, for example: in a multithreaded environment where you want to create a protected section of code within a function.
Scoped lock's use the RAII idiom (resource acquisition is initialisation) to lock a mutex in the constructor and unlock in the destructor, which is useful because if an exception is thrown or return called inside your scoped area, the lock will unlock as it leaves scope.
eg:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void foo()
{
// do some stuff here (not protected by mtx)
{ // lock scope
scoped_lock l(mtx); // acquire mtx
// do some stuff here with the lock acquired
if (some_test)
return; // mtx will automatically be unlocked
if (some_failure)
throw logic_error; // mtx will automatically be unlocked
} // end scope (here the mutex is unlocked)
// do some other stuff here (not protected by mtx)
}