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

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

    I like Luchian's accepted answer, in fact I learned the hard way that he is right, so I do always use braces, even for single-line blocks. However, personally I make an exception when writing a filter, as you are in your example. This:

    int j = 0;
    for (int i = 0 ; i < 100 ; ++i)
    {
        if (i % 2 == 0)
        {
            j++;
        }
    }
    

    looks cluttered to me. It separates the for loop and the if statement into separate actions, when really your intent is a single action: to count all of the integers divisible by 2. In a more expressive language, this could be written something like:

    j = [1..100].filter(_%2 == 0).Count
    

    In languages which lack closures, the filter cannot be expressed in a single statement, but must be a for loop followed by an if statement. However, it is still one action in the mind of the programmer, and I believe that should be reflected in the code, like so:

    int j = 0;
    for (int i = 0 ; i < 100 ; ++i)
      if (i % 2 == 0)
    {
        j++;
    }
    

提交回复
热议问题