5.2 If

The if construct is the most common statement used to decide if a statement (or a statements group) must be executed.

The syntax is the following:

    if (condition)
        statement
where statement, as mentioned before, can be a single statement or a compound statement.

The if construct has a more general form, that has the optional else branch. This specifies the statement that will be executed if the condition evaluates false. The syntax is:

    if (condition)
        statement_1
    else
        statement_2


If the condition in the above example is true, statement_1 will be excuted, if the condition is false, statement_2 will be excuted. The simple example below will illustrate this:

    #include <stdio.h>
    
    int main()
    {
        int x = 5;
    
        if (x < 6) {
            /* If the condition is true, execute the code here */
            printf("This will be printed!\n");
        } else {
            /* If the condition is false, execute the code here */
            printf("This will not be printed.\n");
        }
        
        return 0;
    }

There is also the if else statement which allows you to check multiple conditions. When a program encounters a if statement that uses if else statements, it will check every if/if else statement in order until it finds a true statement. If there are no true statements, it will execute the code with the else block.

Note: If there are multiple true conditions in a if/if else statement, the program will execute the first true condition it comes accross.

See the example below:

    #include <stdio.h>
    
    int main()
    {
        int x = 5;
    
        if (x > 6) {
            /* Not true, keep trying */
            printf("This will not be printed.\n");
        } else if (x == 5) {
            /* The condition is true, the code will be executed! */
            printf("This will be printed!\n");
        } else {
            /* We found a true condition, so else will not be executed. */
            printf("This will not be printed.\n");
        }
    
        return 0;
    }
    
   

This, and other documents, can be downloaded from http://opencbp.sourceforge.net/.

For questions about the Open C Book Project, read the documentation.