blizpasta blizpasta - 5 months ago 42
C++ Question

Do you use curly braces for additional scoping?

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?


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);
  } // Serial port gets closed here.

  for(int i = 0; i < data.size(); i++)