你是否使用花括号来添加范围? [英] Do you use curly braces for additional scoping?

查看:111
本文介绍了你是否使用花括号来添加范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我不知道它可以是像这样做,直到我看到这个SO问题



在上面的链接中,Eli提到他们使用它来折叠他们的代码在逻辑部分,不属于一个函数,类,循环等。通常会折叠起来。



除了这些之外还有什么其他用途?



这是一个好主意,使用大括号来限制变量的范围,并扩大范围,只有在需要(工作在需要访问的基础上)?还是实际上是愚蠢的?



如何使用范围,使您可以在不同范围内使用相同的变量名称,但在同一较大的范围内?或者是更好的做法是重用相同的变量(如果你想使用相同的变量名)和保存释放和分配(我认为一些编译器可以优化这个?)?或者最好一起使用不同的变量名称。

解决方案

如果我使用一个资源,特定时间例如:

  void myfunction()
{
{
// Open串口
SerialPort端口(COM1,9600);
port.doTransfer(data);
} //串口在这里关闭。

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


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

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

这篇关于你是否使用花括号来添加范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆