What's the purpose of using braces (i.e. {}) for a single-line if or loop?

前端 未结 23 1461
独厮守ぢ
独厮守ぢ 2020-11-28 00:33

I\'m reading some lecture notes of my C++ lecturer and he wrote the following:

  1. Use Indentation // OK
  2. Never rely on operator preced
23条回答
  •  不知归路
    2020-11-28 01:11

    I have to admit that not always use {} for single line, but it's a good practise.

    • Lets say you write a code without brackets that looks like this:

      for (int i = 0; i < 100; ++i) for (int j = 0; j < 100; ++j) DoSingleStuff();

    And after some time you want to add in j loop some other stuff and you just do that by alignment and forget to add brackets.

    • Memory dealocation is faster. Lets say you have big scope and create big arrays inside (without new so they are in stack). Those arrays are removing from memory just after you leave scope. But it is possible that you use that array in one place and it will be in stack for a while and be some kind of rubbish. As a stack have limited and quite small size it is possible to exceed stack size. So in some cases it is better to write {} to prevent from that. NOTE this is not for single line but for such a situations:

      if (...) { //SomeStuff... {//we have no if, while, etc. //SomeOtherStuff } //SomeMoreStuff }

    • Third way to use it is similar with second. It just not to make stack cleaner but to open some functions. If you use mutex in long functions usually it is better to lock and unlock just before accessing data and just after finishing reading/writing that. NOTE this way is using if you have some your own class or struct with constructor and destructor to lock memory.

    • What is more:

      if (...) if (...) SomeStuff(); else SomeOtherStuff(); //goes to the second if, but alligment shows it is on first...

    All In All, I cannot say, what is the best way to always use {} for a single line but it is nothing bad to do that.

    IMPORTANT EDIT If you write compiling code brackets for a single line does nothing, but if your code will be interpretated it slowes code for very very slightly. Very slightly.

提交回复
热议问题