Should I use return/continue statement instead of if-else?

前端 未结 13 1884
时光说笑
时光说笑 2020-12-01 10:46

In C, C++ and C# when using a condition inside a function or loop statement it\'s possible to use a continue or return statement as early as possible and g

13条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 10:56

    Do not sacrifice readability for premature optimization.

    For example:

    void function() {
        if( condition ) {
            //do some stuff
        } else {
            //do other stuff
        }
    }
    

    is in most cases binary equivalent to

    void function() {
        if( condition ) {
            //do some stuff
            return;
        }
        //do other stuff
    }
    

    (i.e. the resulting code is probably the same). But the readability of the former is much better, because you can clearly see that the code will to either X or Y.

提交回复
热议问题