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

    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.



Solution 1:[1]

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;
    }

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ryyker