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

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

    The most pertinent example I can think of:

    if(someCondition)
       if(someOtherCondition)
          DoSomething();
    else
       DoSomethingElse();
    

    Which if will the else be paired with? Indentation implies that the outer if gets the else, but that's not actually how the compiler will see it; the inner if will get the else, and the outer if doesn't. You would have to know that (or see it behave that way in debugging mode) to figure out by inspection why this code might be failing your expectations. It gets more confusing if you know Python; in that case you know that indentation defines code blocks, so you would expect it to evaluate according to the indentation. C#, however, doesn't give a flying flip about whitespace.

    Now, that said, I don't particularly agree with this "always use brackets" rule on its face. It makes code very vertically noisy, reducing the ability to read through it quickly. If the statement is:

    if(someCondition)
       DoSomething();
    

    ... then it should be written just like this. The statement "always use brackets" sounds like "always surround mathematical operations with parentheses". That would turn the very simple statement a * b + c / d into ((a * b) + (c / d)), introducing the possibility of missing a close-paren (the bane of many a coder), and for what? The order of operations is well-known and well-enforced, so the parentheses are redundant. You'd only use parentheses to enforce a different order of operations than would normally be applied: a * (b+c) / d for instance. Block braces are similar; use them to define what you want to do in cases where it differs from the default, and is not "obvious" (subjective, but usually pretty common-sense).

提交回复
热议问题