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

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

    Always having curly braces is very simple and robust rule. However the code may look inelegant when there are lot of braces. If the rules allow to omit curly braces then there should be more detailed style rules and more sophisticated tools. Otherwise it may easily result with chaotic and confusing (not elegant) code. Therefore looking single style rule separate from rest of style guides and tools used is likely fruitless. I will just bring some important details about that rule #3 that haven't even been mentioned in other answers.

    First interesting detail is that most proponents of that rule agree to violate it on case of else. In other words they do not demand in review such code:

    // pedantic rule #3
    if ( command == Eat )
    {
        eat();
    }
    else
    {
        if ( command == Sleep )
        {
            sleep();
        }
        else
        {
            if ( command == Drink )
            {
                drink();
            }
            else
            {
                complain_about_unknown_command();
            }
        }
    }
    

    Instead, if they see it they may even suggest to write it like that:

    // not fully conforming to rule #3
    if ( command == Eat )
    {
        eat();
    }
    else if ( command == Sleep )
    {
        sleep();
    }
    else if ( command == Drink )
    {
        drink();
    }
    else
    {
       complain_about_unknown_command();
    }
    

    That is technically violation of that rule since there are no curly brackets between else and if. Such duality of the rule surfaces when to try to apply it to code base automatically with a mindless tool. Indeed, why to argue, just let a tool to apply style automatically.

    Second detail (that is also often forgotten by proponents of that rule) is that the errors that may happen are never only because of violations of that rule #3. Actually those almost always involve violations of rule #1 too (that no one argues with). Again from viewpoint of automatic tools, it is not hard to make a tool that immediately complains when rule #1 is violated and so most of the errors can be caught timely.

    Third detail (that is often forgotten by opponents of that rule) is the confusing nature of empty statement that is represented by single semicolon. Most developers with some experience became confused sooner or later by sole misplaced semicolon or by empty statement that is written using sole semicolon. Two curly braces instead of single semicolon are visually way easier to spot.

提交回复
热议问题