Node:if, Next:, Previous:Decisions, Up:Decisions



if

The first form of the if statement is an all-or-nothing choice: if some condition is satisfied, do something; otherwise, do nothing. For example:

if (condition) statement;

or

if (condition)
{
  compound statement
}

In the second example, instead of a single statement, a whole block of statements is executed. In fact, wherever you can place a single statement in C, you can place a compound statement instead: a block of statements enclosed by curly brackets.

A condition is usually an expression that makes some sort of comparison. It must be either true or false, and it must be enclosed in parentheses: (...). If the condition is true, then the statement or compound statement following the condition will be executed; otherwise, it will be ignored. For example:

if (my_num == 0)
{
  printf ("The number is zero.\n");
}

if (my_num > 0)
{
  printf ("The number is positive.\n");
}

if (my_num < 0)
{
  printf ("The number is negative.\n");
}

The same code could be written more compactly in the following way:

if (my_num == 0) printf ("The number is zero.\n");
if (my_num > 0) printf ("The number is positive.\n");
if (my_num < 0) printf ("The number is negative.\n");

It is often a good idea stylistically to use curly brackets in an if statement. It is no less efficient from the compiler's viewpoint, and sometimes you will want to include more statements later. It also makes if statements stand out clearly in the code. However, curly brackets make no sense for short statements such as the following:

if (my_num == 0) my_num++;

The if command by itself permits only limited decisions. With the addition of else in the next section, however, if becomes much more flexible.