What is the difference between these two code structure? Nested vs single line code

99 views Asked by At
    if (x>0 && x<6) 
    {
        break;
    }
    else if(x>6)
    {
        break;
    }

versus

    if (x>0) 
    {
        if (x<6) 
        {
            break;
        }
    }
    else
    {
        if (x>6) 
        {
            break;
        }
    }
        

Code 1 doesn't work but code 2 does. Why? I'm a super noobie at programming so please any help would be nice. Programming language is C.

2

There are 2 answers

1
Vlad from Moscow On

The else statement in the second code snippet never gets the control for any positive value of x because the condition of the first if statement at once evaluates to logical true.

if (x>0) {
    if (x<6) 
    {
        break;
    }
}
else {
    if (x>6) 
    {
        break;
    }
}

While in the first code snippet the else statement will get the control for any value of x equal to or greater than 6.

That is if x for example is equal to 7 then the condition in the first if statement

if (x>0 && x<6) 
{
    break;
}

evaluates to logical false. So the else statement gets the control and the condition of the if sub-statemen also evaluates to logical true.

else if(x>6)
    {
        break;
    }
1
Elley On

If x is superior to 0, it goes inside if (x>0) , so it's absolutely impossible for it to reach the if (x>6) inside the else.

I don't know what you mean by "it works" "it doesn't work", but, the second example is bad in my opinion, it's unclear, and not each case are treated. While the first one allows for more clarity and case treated.

Your second example basically only treat value between 0 and 6. While the first treat any case between 0 and + int max value or something