I have some Java code that uses curly braces in two ways
// Curly braces attached to an 'if' statement:
if(node.getId() != null)
{
node.getId().apply(this);
}
// Curly braces by themselves:
{
List<PExp> copy = new ArrayList<PExp>(node.getArgs());
for(PExp e : copy)
{
e.apply(this);
}
}
outAMethodExp(node);
What do those stand-alone curly braces after the first if
statement mean?
It is also used for initialization blocks.
They make an inner scope. Variable declared inside these braces is not visible outside of them. This also applies to C/C++.
I agree with the scope limit answer, but would add one thing.
Sometimes you see a construct like that in the code of people who like to fold sections of their code and have editors that will fold braces automatically. They use it to fold up their code in logical sections that don't fall into a function, class, loop, etc. that would usually be folded up.
The bring a scope, copy will not be visible outside of it, so you can declare another variable with same name later. And it can be gathered by the garbage collector right after you exit that scope. In this case copy serves as a temporary variable, so it is a good example.
I'd actually guess that someone forgot an else statement.
There's rarely a good reason to even bother with creating additional block scopes. In this, and most cases, it's far more likely someone may have forgotten to type their control statement than it is that they were doing something clever.
Braces are also useful to reduce the scope in switch/case statements.
But you can write