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

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

    The codebase I'm working on is scattered with code by people with a pathological aversion to braces, and for the people who come along later, it really can make a difference to maintainability.

    The most frequent problematic example I have encountered is this:

    if ( really incredibly stupidly massively long statement that exceeds the width of the editor) do_foo;
        this_looks_like_a_then-statement_but_isn't;
    

    So when I come along and wish to add a then-statement, I can easily end up with this if I'm not careful:

    if ( really incredibly stupidly massively long statement that exceeds the width of the editor) do_foo;
    {
        this_looks_like_a_then-statement_but_isn't;
        i_want_this_to_be_a_then-statement_but_it's_not;
    }
    

    Given that it takes ~1second to add braces and can save you at minimum a few confused minutes debugging, why would you ever not go with the reduced-ambiguity option? Seems like false economy to me.

提交回复
热议问题