Do you use curly braces for additional scoping? [closed]

I mean other than using it when required for functions, classes, if, while, switch, try-catch.

I didn't know that it could be done like this until I saw this SO question.

In the above link, Eli mentioned that "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."

What other uses are there besides those mentioned?

Is it a good idea to use curly braces to limit the scope of your variables and expand the scope only if required (working on a "need-to-access" basis)? Or is it actually silly?

How about using scopes just so that you can use the same variable names in different scopes but in the same bigger scope? Or is it a better practise to reuse the same variable (if you want to use the same variable name) and save on deallocating and allocating (I think some compilers can optimise on this?)? Or is it better to use different variable names altogether?


Solution 1:

I do if I am using a resource which I want to free at a specific time eg:

void myfunction()
{
  {
  // Open serial port
     SerialPort port("COM1", 9600);
     port.doTransfer(data);
  } // Serial port gets closed here.

  for(int i = 0; i < data.size(); i++)
     doProcessData(data[i]);
  etc...
}

Solution 2:

I would not use curly braces for that purpose for a couple reasons.

  1. If your particular function is big enough that you need to do various scoping tricks, perhaps break the function into smaller sub-functions.

  2. Introducing braces for scoping to reuse variable names is only going to lead to confusion and trouble in code.

Just my 2 cents, but I have seen a lot of these types of things in other best practice materials.