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

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

    It's very easy to accidentally change control-flow with comments if you do not use { and }. For example:

    if (condition)
      do_something();
    else
      do_something_else();
    
    must_always_do_this();
    

    If you comment out do_something_else() with a single line comment, you'll end up with this:

    if (condition)
      do_something();
    else
      //do_something_else();
    
    must_always_do_this();
    

    It compiles, but must_always_do_this() isn't always called.

    We had this issue in our code base, where someone had gone in to disable some functionality very quickly before release. Fortunately we caught it in code review.

提交回复
热议问题