if Statements

suggest change

One of the simplest ways to control program flow is by using if selection statements. This statement decides whether a block of code is executed.

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 the block, the braces have to be 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 puts and a++ if both a and b are greater than 1.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents