What is happening in an “If(..||..)” and “If(…&&…)” construct internally?

后端 未结 6 1989
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 18:29

I was just wondering what happens inside of an \"if OR\" and \"if AND\". I have a feeling that it\'s just syntactic sugar to use &

6条回答
  •  旧巷少年郎
    2020-12-15 18:54

    The code:

    if(a)
        if(b)
            if(c)
                DoSomething();
    

    is a logical (but not "practical") equivalent for:

    if(a && b && c)
        DoSomething();
    

    As for the OR operator you've got it a bit wrong. A logical (but, again, not "practical") equivalent for:

    if(a || b || c)
        DoSomething();
    

    would be:

    if(a)
        DoSomething();
    else if(b)
        DoSomething();
    else if(c)
        DoSomething();
    

    By practical difference I understand any resulting code differences introduced by the compiler (refer to other answers for details).

提交回复
热议问题