if Statement

Previously, we have learned that the actual work in a program is performed by expressions. This lesson further elaborates on that concept by explaining an important control structure that uses logical expressions.

Control statements #

All of the expressions of all of the programs that we’ve seen so far have started with the main() function and were executed until the end of the main.

Control statements are features that affect the execution of expressions. These statements don’t produce values and don’t have side effects themselves. They determine whether and in what order the expressions are executed. Control statements sometimes use logical expressions when making such decisions.

Note: Other programming languages may have different definitions for expression and statement, while some others may not have a distinction at all.

The if block and its scope #

The if statement decides which piece of code to execute based on some condition becoming true. It makes this decision by evaluating a logical expression. It has the same meaning as the English word “if,” as in the phrase “if there is coffee, then I will drink coffee”.

if is a keyword in D that is followed by a logical expression in parentheses. If the value of that logical expression is true, then it executes the block of code that is enclosed in the curly brackets. Conversely, if the logical expression is false, it does not execute the statements within the curly brackets.

The area within the curly brackets is called a scope, and all of the code that is in that scope is called a block of code.
Here is the syntax of the if statement:

if (a_logical_expression) {
    // ... expression(s) to execute if true
}

Example #

This program displays “drink coffee and wash the cup” if “there is coffee”.

Get hands-on with 1200+ tech skills courses.