Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you use code blocks?

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:

  • Do you use curly braces for additional scoping? (https://stackoverflow.com/questions/249009/do-you-use-curly-braces-for-additional-scoping)
like image 753
Lucas Jones Avatar asked Dec 09 '22 21:12

Lucas Jones


2 Answers

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.

like image 182
Paul Ruane Avatar answered Dec 17 '22 20:12

Paul Ruane


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.

like image 40
Adam Robinson Avatar answered Dec 17 '22 20:12

Adam Robinson