Replacing nested if statements

前端 未结 11 1911
春和景丽
春和景丽 2020-12-23 20:44

This is related to a chapter from beautiful code. And in that chapter I read about the nested ifs.

The author was talking about deeply nested if

11条回答
  •  既然无缘
    2020-12-23 21:43

    Nested if are equivalent to the logical operator AND

    if (condition1)
    {
        if (function(2))
        {
            if (condition3)
            {
                // do something
            }
        }
    }
    

    Equivalent code:

    if (condition1 && function(2) && condition3)
    {
        // do something
    }
    

    In both cases, when an expression evaluates false, the subsequent expression will not be evaluated. For example, if condition1 is false, the function() will not be called, and condition3 won't be evaluated.

提交回复
热议问题