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

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

    I am using {} everywhere except a few cases where it's obvious. Single line is one of the cases:

    if(condition) return; // OK
    
    if(condition) // 
       return;    // and this is not a one-liner 
    

    It may hurt you when you add some method before return. Indentation indicates that return is executing when condition is met, but it will return always.

    Other example in C# with using statment

    using (D d = new D())  // OK
    using (C c = new C(d))
    {
        c.UseLimitedResource();
    }
    

    which is equivalent to

    using (D d = new D())
    {
        using (C c = new C(d))
        {
            c.UseLimitedResource();
        }
    }
    

提交回复
热议问题