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

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

    There are a number of possible ways of writing control statements; certain combinations of them may co-exist without impairing legibility, but other combinations will cause trouble. The style

    if (condition)
      statement;
    

    will co-exist comfortably with some of the other ways of writing control statements, but not so well with others. If multi-line controlled statements are written as:

    if (condition)
    {
      statement;
      statement;
    }
    

    then it will be visually obvious which if statements control a single line and which ones control multiple lines. If, however, multi-line if statements are written as:

    if (condition) {
      statement;
      statement;
    }
    

    then the likelihood of someone trying to extend a single-statement if constructs without adding the necessary braces may be much higher.

    The single-statement-on-next line if statement may also be problematic if the codebase makes significant use of the form

    if (condition) statement;
    

    My own preference is that having the statement on its own line generally enhances legibility except in cases where there are many if statements with similar control blocks, e.g.

    if (x1 > xmax) x1 = xmax;
    if (x1 < xmin) x1 = xmin;
    if (x2 > xmax) x2 = xmax;
    if (x2 < xmin) x2 = xmin;
    etc.
    

    in which case I will generally precede and follow such groups of if statements with a blank line to visually separate them from other code. Having a range of statements that all start with if at the same indentation will then provide a clear visual indication that there's something unusual.

提交回复
热议问题