The if-else allows you to make simple either-or choices. The syntax is:
if (expression)
statement1
else
statement2
where the else part is optional.
The expression is evaluated and statement1 is evaluated if the result is true. Otherwise statement2 is evaluated. Control then passes on to the next statement.
In C (unusually for an imperative language) all expressions have a value, which is usually ignored. This is one case where it is not and you will meet others later.
For example, if you want to test if variable x has the value zero, you could write
if (x)
rather than
if (x==0)
However this can sometimes be confusing. In general write what you mean, rather than writing something which has the same effect.
Note the use of == for the equality operator and appreciate how this differs from assignment (=).
Example
if ( x < y )
printf("x is less than y\n");
else
printf("x is greater than or equal to y\n");
Note the semi-colon after the if part: the syntax requires a statement, not an expression. In general you might want:
if ( x < y )
{
/* lots of statements */
}
else
{
/* lots more statements */
}
Note no semi-colon is needed because a block is a statement.
maspjw@