if (x>0 && x<6)
{
break;
}
else if(x>6)
{
break;
}
vs
if (x>0) {
if (x<6)
{
break;
}
}
else {
if (x>6)
{
break;
}
}
Code 1 doesnt work but code 2 does. Why? Im super noobie at programming so please any help would be nice. Programming language is C.
CodePudding user response:
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;
}
CodePudding user response:
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