Is it a good style to place curly brackets around logical parts of sequential code to structure it?

An advantage would be, that you can collapse these blocks in an editor like vim and get a better overview of your code.

I talk about code, which does not belong in a separate function, due to parameter passing overhead, or to many one-time-only called functions or simmilar.


struct abc {
  int a = 1;
  string b = "foo";
  char c = 'c';

abc myabc;
//assigning variables
   myabc.a = 111;
   myabc.c = 'x';

can be collapsed to (vim):

abc myabc;
//assigning variables

I know about initializer lists, and the example is of course made up. Other examples would be some printing, or a big gnu longopts block at the beginning of the main method or looking for some values in a std::map cache-variable.


1 Answer 1


The only reason to use a block/compound statement aside from control flow constructs like if/else/while is if you need a nested scope, e.g. to limit the lifetime of a local variable. The block specifies when the destructors will run which may be very important. E.g. you might use a class that acquires a lock via RAII, and you want to release it as soon as possible. Then:

  Lock acquire_some_resource{};
}  // destructor releases lock

Code blocks are not a suitable mechanism for structuring code because they will always (misleadingly) suggest they are used because of variable visibility or lifetime.


  • use empty lines between unrelated statements to add visual rhythm to your code.
  • extract details into a separate function if it distracts from the main purpose. Pass arguments by reference if you are concerned about “parameter passing overhead”. You can also make sure the separate function has internal linkage, e.g. by declaring it in an anonymous namespace.
  • I would argue that: con argument presented has lesser practical value than pro stated in the question. i.e. code_readability_difference = convenient block collapsing - "(misleadingly) suggest they are used because of variable visibility or lifetime " > 0 But, it's just my taste :).
    – hardyVeles
    Mar 22, 2020 at 4:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.