What is the purpose of anonymous { } blocks in C style languages (C, C++, C#)
Example -
void function()
{
{
int i = 0;
i = i + 1;
}
It limits the scope of variables to the block inside the { }.
Scoping of course. (Has that horse been beaten to death yet?)
But if you look at the language definition, you see patterns like:
It simplifies the language syntax that compound-statement is just one of several possible statement's.
compound-statement: { statement-listopt }
statement-list:
statement:
I use it for blocks of code that need temporary variables.
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;
As far as I understand, they are simply for scoping. They allow you to reuse variable names in the parent/sibling scopes, which can be useful from time to time.
EDIT: This question has in fact been answered on another Stack Overflow question. Hope that helps.
As the previous posters mentioned, it limits the use of a variable to the scope in which it is declared.
In garbage collected languages such as C# and Java, it also allows the garbage collector to reclaim memory used by any variables used within the scope (although setting the variables to null would have the same effect).
{
int[] myArray = new int[1000];
... // Do some work
}
// The garbage collector can now reclaim the memory used by myArray