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

前端 未结 23 1372
独厮守ぢ
独厮守ぢ 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:16

    One option for helping to prevent the errors that have been described above is to inline what you want to happen when you don't use braces. It makes it much harder to not notice the errors when you try to modify the code.

    if (condition) doSomething();
    else doSomethingElse();
    
    if (condition) doSomething();
        doSomething2(); // Looks pretty obviously wrong
    else // doSomethingElse(); also looks pretty obviously wrong
    

提交回复
热议问题