C Language Selection Statements if () Statements


Example

One of the simplest ways to control program flow is by using if selection statements. Whether a block of code is to be executed or not to be executed can be decided by this statement.

The syntax for if selection statement in C could be as follows:

if(cond) 
{
  statement(s);  /*to be executed, on condition being true*/
}

For example,

if (a > 1) {
    puts("a is larger than 1");
}

Where a > 1 is a condition that has to evaluate to true in order to execute the statements inside the if block. In this example "a is larger than 1" is only printed if a > 1 is true.

if selection statements can omit the wrapping braces { and } if there is only one statement within the block. The above example can be rewritten to

if (a > 1)
    puts("a is larger than 1");

However for executing multiple statements within block the braces have to used.

The condition for if can include multiple expressions. if will only perform the action if the end result of expression is true.

For example

if ((a > 1) && (b > 1)) {
    puts("a is larger than 1");
    a++;
}

will only execute the printf and a++ if both a and b are greater than 1.