Do you use curly braces for additional scoping? [c

2019-01-07 09:15发布

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?

13条回答
对你真心纯属浪费
2楼-- · 2019-01-07 10:08

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...
}
查看更多
登录 后发表回答