Even in C, you can open the bracket at any point where approval is allowed.
This allows you to declare and use new variables without interfering with the scope. For instance:
... code before ... { int i = 0, sum = 0; while (i < n) { sum += dothis(data[i++]); } dothat(sum); } ... code after ...
the two variables i and sum have nothing to do with variables with the same name in the enclosing area: these two variables are created when the block is entered and destroyed when the block is exited (instead, n and data defined outside). This can help readability by avoiding the distinction between declaration and use or between declaration and initialization (in old C, you were not allowed to enter a variable declaration immediately before use ... all locals should have been declared at the beginning of the function: annoying problem if you haven't already know the meanings to give them).
If you are in C ++ and these block-local variables are of class type, the constructor is called when a block is entered (and not when a function is entered) and is immediately destroyed when the block exits. This can be very useful, for example, for locks.
{ Lock mylock(resource); use_resource(); }
source share