Reputation: 29116
I always think it is very convenient in C to use brace blocks as closure blocks. The main reason is that I can do a better use of the syntax folding in my IDE without adding extra complexity to my code (such as adding additional functions).
// Block 1
{
int i;
i = some_work(i);
j = i;
}
// Block 2
{
...
}
I don't know if this is a correct solution in C. Is there any programming standards that mention closure blocks in C?
Upvotes: 1
Views: 143
Reputation: 33273
Most programming standards advocate for dividing long functions into shorter ones and the use of empty lines to separate a function inte smaller units.
The two main reasons for this is readability and testability.
If you divide a long function into smaller ones, each smaller function can be unit tested separately.
What you are doing is better than just having a large function, but you miss out on the testability part.
Depending on how your code looks, you may also be missing out on readability. Remember that a function has a name that describes it. Blocks don't have names, so you would need a comment to describe it.
If used correctly, blocks can be used to improve readability. However, the same is true for a simple blank line. The advantage of a block over an empty line is that it limits the scope for local variables, thus increasing readability.
So, for each block you create, you should consider whether it corresponds to an empty line or a function call. In the latter case, convert the block to a separate function.
Upvotes: 3
Reputation: 399949
Those aren't closures, they're just scope blocks.
You can't use them like you can with closures in languages that support closures natively. You can't store a reference to a such a block and execute it later, for instance.
They're less useful in C99, since you can declare new variables anywhere now.
Upvotes: 3