The if-then-else statement is a shorter and more elegant way of testing two logically opposite conditions. Using the if-then-else statement, the if-then section enables us to execute a piece of code if the expression evaluates to True, and the else section enables us to execute a piece of code if the same expression evaluates to False. The syntax of the if-then-else statement is:
if expression then statement else statement;
If you want to execute more statements, write them inside a block:
if expression then begin statement1; statementN; end else begin statement1; statementN; end;
Note | The statement or block that precedes the reserved word else doesn't end with a semicolon. If you add a semicolon, you will get a compiler error. |
A simple example of the if-then-else statement is an application that asks for a user name. The if-then section tests if the user entered a valid user name, and the else section is used to display a message if the user failed to enter a valid user name.
Listing 3-3: The if-then-else statement
program Project1; {$APPTYPE CONSOLE} uses SysUtils; var UserName: string; begin Write('Please enter your name: '); ReadLn(UserName); if UserName <> '' then WriteLn('Hello, ', UserName, '!') else WriteLn('Invalid user name!'); ReadLn; end.
The if-then-else statement in this example assumes the user name is valid if the value entered in the UserName variable is not an empty string. In Delphi, an empty string is denoted by two single quote marks. The UserName variable in this example can be an empty string if the user presses the Enter key without entering the user name. Since an empty string isn't a valid user name, the if-then-else statement evaluates to False and executes the WriteLn statement in the else section.
Writing an if-then-else statement can be time-consuming since it can consist of many lines of code. To speed up the typing process, the developers at Borland added code templates to Delphi.
If you want to use the code template for the if-then-else statement, type the shortcut "ifeb" (without the quotation marks) in the Code Editor and press Ctrl+J. When you press Ctrl+J, the shortcut is replaced with the appropriate code template, and in this case it's an if-then-else statement with blocks, as shown in Figure 3-2.
Figure 3-2: Using code templates
Another way of using code templates is to press Ctrl+J without typing a shortcut. This displays a list of all code templates available.
Figure 3-3: The code template list