I've come across a bit of code that contains a couple code blocks, delineated with curly braces {}
. There is no line before the code blocks marking them as part of if
statements, function definitions, or anything else. Just a code block floating in the middle of a function. Is there any meaning to this? gcc
seems perfectly happy going through the code; I can only imagine it is some way to allow the original coder to split up blocks of functionality visually...
It creates a scope. Are there automatic variables defined inside the blocks? If so, then the scope of those variables is confined to the block. It's useful for temporary variables that you don't want polluting the rest of the function, and it's also useful when writing C89, where variable definitions must be at the start of a block.
So, instead of:
int main() {
int a = 0;
int b;
int i;
for (i = 1; i < 10; ++i) {
a += i;
}
b = a * a;
// do something with a and b
}
You could have:
int main() {
int a = 0;
{
int i;
for (i = 1; i < 10; ++i) {
a += i;
}
}
{
int b = a * a;
// do something with a and b
}
}
Obviously if you're doing this, you also have to ask yourself if the blocks wouldn't be better off as separate functions.
Standalone curly braces are used for scoping—any variables declared in a block aren't visible outside it.
If the code blocks contain local variable declarations (your description is not clear about what's inside), they may be there to limit the scope of those variables. I.e.
int i = ...;
// i is visible here
{
int j = ...;
// both i and j are visible here
}
// j went out of scope, only i is visible here
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