Reputation: 2856
When doing a code review for a colleague today I saw a peculiar thing. He had surrounded his new code with curly braces like this:
Constructor::Constructor()
{
// Existing code
{
// New code: do some new fancy stuff here
}
// Existing code
}
What is the outcome, if any, from this? What could be the reason for doing this? Where does this habit come from?
The environment is embedded devices. There is a lot of legacy C code wrapped in C++ clothing. There are a lot of C turned C++ developers.
There are no critical sections in this part of the code. I have only seen it in this part of the code. There are no major memory allocations done, just some flags that are set, and some bit twiddling.
The code that is surrounded by curly braces is something like:
{
bool isInit;
(void)isStillInInitMode(&isInit);
if (isInit) {
return isInit;
}
}
(Don't mind the code, just stick to the curly braces... ;) ) After the curly braces there are some more bit twiddling, state checking, and basic signaling.
I talked to the guy and his motivation was to limit the scope of variables, naming clashes, and some other that I couldn't really pick up.
From my point of view this seems rather strange and I don't think that the curly braces should be in our code. I saw some good examples in all the answers on why one could surround code with curly braces, but shouldn't you separate the code into methods instead?
Upvotes: 213
Views: 57310
Reputation: 19333
I agree with ruakh. If you want a good explanation of the various levels of scope in C, check out this post:
Various Levels of Scope in C Application
In general, the use of "Block scope" is helpful if you want to just use a temporary variable that you don't have to keep track of for the lifetime of the function call. Additionally, some people use it so you can use the same variable name in multiple locations for convenience, though that's not generally a good idea. E.g.:
int unusedInt = 1;
int main(void) {
int k;
for(k = 0; k<10; k++) {
int returnValue = myFunction(k);
printf("returnValue (int) is: %d (k=%d)",returnValue,k);
}
for(k = 0; k<100; k++) {
char returnValue = myCharacterFunction(k);
printf("returnValue (char) is: %c (k=%d)",returnValue,k);
}
return 0;
}
In this particular example, I have defined returnValue twice, but since it is just at block scope, instead of function scope (i.e., function scope would be, for example, declaring returnValue just after int main(void))
, I don't get any compiler errors, as each block is oblivious to the temporary instance of returnValue declared.
I can't say that this is a good idea in general (i.e., you probably shouldn't reuse variable names repeatedly from block-to-block), but in general, it saves time and lets you avoid having to manage the value of returnValue across the entire function.
Finally, please note the scope of the variables used in my code sample:
int: unusedInt: File and global scope (if this were a static int, it would only be file scope)
int: k: Function scope
int: returnValue: Block scope
char: returnValue: Block scope
Upvotes: 10
Reputation: 52107
This is the same as an if
(or while
, etc.) block, just without if
. In other words, you introduce a scope without introducing a control structure.
This "explicit scoping" is typically useful in following cases:
using
.Example 1:
{
auto my_variable = ... ;
// ...
}
// ...
{
auto my_variable = ... ;
// ...
}
If my_variable
happens to be a particularly good name for two different variables that are used in isolation from each other, then explicit scoping allows you to avoid inventing a new name just to avoid the name clash.
This also allows you to avoid using my_variable
out of its intended scope by accident.
Example 2:
namespace N1 { class A { }; }
namespace N2 { class A { }; }
void foo() {
{
using namespace N1;
A a; // N1::A.
// ...
}
{
using namespace N2;
A a; // N2::A.
// ...
}
}
Practical situations when this is useful are rare and may indicate the code is ripe for refactoring, but the mechanism is there should you ever genuinely need it.
Example 3:
{
MyRaiiClass guard1 = ...;
// ...
{
MyRaiiClass guard2 = ...;
// ...
} // ~MyRaiiClass for guard2 called.
// ...
} // ~MyRaiiClass for guard1 called.
This can be important for RAII in cases when the need for freeing resources does not naturally "fall" onto boundaries of functions or control structures.
Upvotes: 19
Reputation: 1448
Another example of usage is UI-related classes, especially Qt.
For example, you have some complicated UI and a lot of widgets, each of them got its own spacing, layout, etc. Instead of naming them space1, space2, spaceBetween, layout1, ...
you can save yourself from non-descriptive names for variables that exist only in two-three lines of code.
Well, some might say that you should split it in methods, but creating 40 non-reusable methods doesn't look ok - so I decided to just add braces and comments before them, so it looks like logical block.
Example:
// Start video button
{
<Here goes the code >
}
// Stop video button
{
<...>
}
// Status label
{
<...>
}
I can't say that's the best practice, but it's good one for legacy code.
Got these problems when a lot of people added their own components to UI and some methods became really massive, but it's not practical to create 40 onetime-usage methods inside class that already messed up.
Upvotes: 4
Reputation: 361254
The extra braces are used to define the scope of the variable declared inside the braces. It is done so that the destructor will be called when the variable goes out of scope. In the destructor, you may release a mutex (or any other resource) so that other could acquire it.
In my production code, I've written something like this:
void f()
{
// Some code - MULTIPLE threads can execute this code at the same time
{
scoped_lock lock(mutex); // Critical section starts here
// Critical section code
// EXACTLY ONE thread can execute this code at a time
} // The mutex is automatically released here
// Other code - MULTIPLE threads can execute this code at the same time
}
As you can see, in this way, you can use scoped_lock
in a function and at the same time, can define its scope by using extra braces. This makes sure that even though the code outside the extra braces can be executed by multiple threads simultaneously, the code inside the braces will be executed by exactly one thread at a time.
Upvotes: 104
Reputation: 399703
It's sometimes nice since it gives you a new scope, where you can more "cleanly" declare new (automatic) variables.
In C++ this is maybe not so important since you can introduce new variables anywhere, but perhaps the habit is from C, where you could not do this until C99. :)
Since C++ has destructors, it can also be handy to have resources (files, mutexes, or whatever) automatically released as the scope exits, which can make things cleaner. This means you can hold on to some shared resource for a shorter duration than you would if you grabbed it at the start of the method.
Upvotes: 317
Reputation: 16195
This is really useful when using scoped locks in conjunction with critical sections in multithreaded programming. Your scoped lock initialised in the curly braces (usually the first command) will go out of scope at the end of the end of the block and so other threads will be able to run again.
Upvotes: 15
Reputation: 95306
As others have pointed out, a new block introduces a new scope, enabling one to write a bit of code with its own variables that don't trash the namespace of the surrounding code, and doesn't use resources any longer than necessary.
However, there's another fine reason for doing this.
It is simply to isolate a block of code that achieves a particular (sub)purpose. It is rare that a single statement achieves a computational effect I want; usually it takes several. Placing those in a block (with a comment) allows me tell the reader (often myself at a later date):
e.g.
{ // update the moving average
i= (i+1) mod ARRAYSIZE;
sum = sum - A[i];
A[i] = new_value;
sum = sum + new_value;
average = sum / ARRAYSIZE ;
}
You might argue I should write a function to do all that. If I only do it once, writing a function just adds additional syntax and parameters; there seems little point. Just think of this as a parameterless, anonymous function.
If you are lucky, your editor will have a fold/unfold function that will even let you hide the block.
I do this all the time. It is great pleasure to know the bounds of the code I need to inspect, and even better to know that if that chunk isn't the one I want, I don't have to look at any of the lines.
Upvotes: 58
Reputation: 67713
Everyone else already covered correctly the scoping, RAII etc. possiblities, but since you mention an embedded environment, there is one further potential reason:
Maybe the developer doesn't trust this compiler's register allocation or wants to explicitly control the stack frame size by limiting the number of automatic variables in scope at once.
Here isInit
will likely be on the stack:
{
bool isInit;
(void)isStillInInitMode(&isInit);
if (isInit) {
return isInit;
}
}
If you take out the curly braces, space for isInit
may be reserved in the stack frame even after it could potentially be reused: if there are lots of automatic variables with similarly localized scope, and your stack size is limited, that could be a problem.
Similarly, if your variable is allocated to a register, going out of scope should provide a strong hint that register is now available for re-use. You'd have to look at the assembler generated with and without the braces to figure out if this makes a real difference (and profile it - or watch for stack overflow - to see if this difference really matters).
Upvotes: 16
Reputation: 7541
After viewing the code in the edit, I can say that the unnecessary brackets are probably (in the original coders view) to be 100% clear what will happen during the if/then, even tho it is only one line now, it might be more lines later, and the brackets guarantee you wont make an error.
{
bool isInit;
(void)isStillInInitMode(&isInit);
if (isInit) {
return isInit;
}
return -1;
}
if the above was original, and removing "extras" woudl result in:
{
bool isInit;
(void)isStillInInitMode(&isInit);
if (isInit)
return isInit;
return -1;
}
then, a later modification might look like this:
{
bool isInit;
(void)isStillInInitMode(&isInit);
if (isInit)
CallSomethingNewHere();
return isInit;
return -1;
}
and that, would of course, cause an issue, since now isInit would always be returned, regardless of the if/then.
Upvotes: 5
Reputation: 22810
So, why to use "unnecessary" curly braces?
#pragma
, or defining "sections" that can be visualized)P.S. It's not BAD code; it's 100% valid. So, it's rather a matter of (uncommon) taste.
Upvotes: 6
Reputation: 131
I think others have covered scoping already, so I'll mention the unnecessary braces might also serve purpose in the development process. For example, suppose you are working on an optimization to an existing function. Toggling the optimization or tracing a bug to a particular sequence of statements is simple for the programmer -- see the comment prior to the braces:
// if (false) or if (0)
{
//experimental optimization
}
This practice is useful in certain contexts like debugging, embedded devices, or personal code.
Upvotes: 13
Reputation: 183201
One possible purpose is to control variable scope. And since variables with automatic storage are destroyed when they go out of scope, this can also enable a destructor to be called earlier than it otherwise would.
Upvotes: 180
Reputation: 4674
One reason could be that the lifetime of any variables declared inside the new curly braces block is restricted to this block. Another reason that comes to mind is to be able to use code folding in the favourite editor.
Upvotes: 24