Team LiB
Previous Section Next Section

1.8. if...else

You can use the if...else statement to execute a block of statements depending on a condition. For example, suppose we want the value of variable port_open to be 1 if the value of the variable success is positive. Otherwise, we want the value of port_open to be -1. Our if...else statement would be as follows:

if (success>0)
{
    port_open=1;
}
else
{
    port_open=-1;
}

Because we have only one statement within the if and else blocks, the braces { and } are optional, so our statement would have also worked if we had not enclosed our assignment statements within the braces.

It is also possible to nest if...else statements. For example, suppose we want to assign the value -2 to port_open if success equals -10, or the value 0 to port_open if success is less than 1. Otherwise, we want to assign the value 1 to port_open. In this case, our if..else statement would be as follows:

if (success==-10)
{
    port_open=-2;
}
else if (success<1)
{
    port_open=0;
}
else
{
    port_open=1;
}

    Team LiB
    Previous Section Next Section