Search code examples
c#c++

Multiple Conditions in If Statement or Splitting


when i am using if statements with multiple conditions, how are they managed in the compiler?

A) Will it ignore the second Statement, if the first statement is not fulfilled or vice versa?

If(time > 3.0 && hitEnabled)

B) Late Defintions are often recommended, so should i prefere to use one condition in if statements?

if(time > 3.0)
    if(hitEnabled)

Thanks!


Solution

  • if(time > 3.0 && hitEnabled)
    

    In above statement hitEnabled will not be evaluated when time > 3.0 is false.

    This is called short-circuit.

    Following statement will evaluate hitEnabled even when time > 3.0 is false but returns true when both operands are true.

    if(time > 3.0 & hitEnabled)//note bitwise &
    

    if(time > 3.0)
        if(hitEnabled)
    

    Nested if statements are helpful when you need first condition to be checked many times etc.

    if(time > 3.0 && hitEnabled)
    {
    //DoSomething1
    }
    if(time > 3.0 && flag)
    {
    //DoSomething2
    }
    

    This can be re written with nested if statements as follows

    if(time > 3.0)
    {
        if(hitEnabled)
        {
        //DoSomething1
        }
        if(flag)
        {
        //DoSomething2
        }
    }
    

    In this case I prefer nested if statement to avoid unnecessary checks