当你用code块? [英] When do you use code blocks?
问题描述
当你使用C / C ++ / C#等code块?我知道他们背后的理论理性,但是当你使用它们在实际程序?
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?
修改:我刚才已经意识到,我使用它们开关
语句,其中的变量,否则将在同一范围(GRR的东西如我
):
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; }
等 (只是为了澄清,在switch语句中,额外的括号的不是的要求。)
etc (Just to clarify, in a switch statement, the extra braces are NOT required.)
相关报道:
推荐答案
我有时候会,但很少使用明火code块限制范围。例如,采取以下code:
I sometimes, but rarely, use naked code blocks to limit scope. For example, take the following code:
double bedroomTemperature = ReadTemperature(Room.Bedroom);
database.Store(Room.Bedroom, bedroomTemperature);
double bathroomTemperature = ReadTemperature(Room.Bathroom);
database.Store(Room.Bedroom, bedroomTemperature);
在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:
{
double bedroomTemperature = ReadTemperature(Room.Bedroom);
database.Store(Room.Bedroom, bedroomTemperature);
}
{
double bathroomTemperature = ReadTemperature(Room.Bathroom);
database.Store(Room.Bedroom, bedroomTemperature);
}
那么编译器(甚至是IDE,如果它有足够的智能)会看准了这一点。
Then the compiler (or even IDE if it is intelligent enough) would have spotted this.
然而,90%的code,可重构,使裸体阻止不必要的时间,例如:上述code会更好写成循环或两次调用读取并存储该温度的方法:
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:
foreach (Room room in [] { Room.Bedroom, Room.Bathroom })
{
double temperature = ReadTemperature(room);
database.Store(room, temperature);
}
裸体块是偶尔有用,但。
Naked blocks are useful on occasion though.
这篇关于当你用code块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!