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

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

    I consider the first one to be clear then second. It gives the feeling of closing instructions, with little code is fine when code gets complex {...} helps a lot even if it is endif or begin...end

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

提交回复
热议问题