什么时候使用代码块?
什么时候在 C/C++/C# 等中使用代码块? 我知道它们背后的理论原因,但是什么时候在实际程序中使用它们?
编辑:我刚刚意识到我在 switch
语句中使用它们,否则变量将在相同的范围内(对于像 i
这样的东西,grr ):
switch (x) { case "abc": { /* code */ } break; }
ETC (只是为了澄清,在 switch 语句中,不需要额外的大括号。)
相关:
When do you use code blocks in C/C++/C#, etc.? I know the theoretical reason behind them, but when do you use them in real programs?
EDIT: I have just realised that I use them in switch
statements, where variables would otherwise be in the same scope (grr for things like i
):
switch (x) { case "abc": { /* code */ } break; }
etc
(Just to clarify, in a switch statement, the extra braces are NOT required.)
Related:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我有时(但很少)使用裸代码块来限制范围。 例如,采用以下代码:
乍一看,该代码看起来不错,但包含一个微妙的复制粘贴错误。 在数据库中,我们存储了两个读数的卧室温度。 如果它被写成:
那么编译器(甚至是 IDE,如果它足够智能)就会发现这一点。
然而,90% 的情况下,可以重构代码以使裸块变得不必要,例如,上面的代码最好编写为一个循环或两次调用读取和存储温度的方法:
尽管裸块有时很有用。
I sometimes, but rarely, use naked code blocks to limit scope. For example, take the following code:
The code looks fine at first glance, but contains a subtle copy-pasta error. In the database we have stored the bedroom temperature for both readings. If it had been written as:
Then the compiler (or even IDE if it is intelligent enough) would have spotted this.
However, 90% of the time the code can be refactored to make the naked blocks unnecessary, e.g. the above code would be better written as a loop or two calls to a method that reads and stores the temperature:
Naked blocks are useful on occasion though.
我对开关块做了同样的事情,尽管这不是必需的。 一般来说,我使用代码块,它们要么使代码更具可读性(无论是通过为相似的代码块提供相似的外观还是只是缩进),要么它们正确地作用域变量。
I do the same thing with switch blocks, even though it isn't required. In general, I use code blocks where they either make code more readable (whether that's through giving similar blocks of code a similar appearance or just getting the indenting) or they properly scope variables.
通过使用代码块和 RAII 对象,您可以在 C++ 中获得类似
finally
的行为。无论什么原因导致我们离开块,都会在析构函数中释放文件描述符。
(就我个人而言,我仍在尝试实践这一点。我的 c 根紧紧抓住我的习惯......)
You can get a
finally
like behavior in C++ by using code blocks and RAII objects.will release the file descriptor in the destructor no matter what causes us to leave the block.
(Personally, I'm still trying to make a practice of this. My c roots hold a death grip on my habits...)
除了明显的(“当语法需要时”,例如在 switch 或 try catch finally 中),
每当您需要将 2 个或更多语句组成的块视为原子单元时
In addition to the obvious ("when required by syntax", like in a switch or a try catch finally),
Whenever you need to treat a block of 2 or more statements as an atomic unit