When do you use code blocks?

2020-02-14 04:18发布

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:

4条回答
ら.Afraid
2楼-- · 2020-02-14 04:43

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);

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);
}

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:

foreach (Room room in [] { Room.Bedroom, Room.Bathroom })
{
    double temperature = ReadTemperature(room);
    database.Store(room, temperature);
}

Naked blocks are useful on occasion though.

查看更多
Root(大扎)
3楼-- · 2020-02-14 04:45

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

查看更多
▲ chillily
4楼-- · 2020-02-14 04:49

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.

查看更多
劳资没心,怎么记你
5楼-- · 2020-02-14 04:56

You can get a finally like behavior in C++ by using code blocks and RAII objects.

{
   std::fstream f(filename)
   ...
}

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...)

查看更多
登录 后发表回答