1. Computing

The Traps of The If Then Else Statement in Delphi Code

Beginner Delphi Developers: Watchout for If Then Else Traps

By

Article submitted by Marcus Junglas

In Delphi, the if statement is used to test for a condition and then execute sections of code based on whether that condition is True or False.

A general if-then-else statement looks like :

 if <condition> then <true block> else <false block>;
 
Both the "true block" and the "false block" can either be a simple statement or a structured statement (surrounded with a begin-end pair).

Let's consider one example using nested if statements:

 j := 50;
 if j >= 0 then
   if j = 100 then Caption := 'Number is 100!'
 else
   Caption := 'Number is NEGATIVE!';v
 
What will be the value of "Cation"? Answer: "'Number is NEGATIVE!" Did not expect that?

Note that the compiler does not take your formatting into account, you could have written the above as:

 j := 50;
 if j >= 0 then
 if j = 100 then Caption := 'Number is 100!'
 else
 Caption := 'Number is NEGATIVE!';v
 
or even as (all in one line):
 j := 50; if j >= 0 then if j = 100 then Caption := 'Number is 100!'
 else
 Caption := 'Number is NEGATIVE!';v
 
The ";" marks the end of a statement.

The compiler will read the above statement as:

 j := 50;
 if j >= 0 then
   if j = 100 then
     Caption := 'Number is 100!'
   else
     Caption := 'Number is NEGATIVE!';
 
or to be more precise:
 j := 50;
 if j >= 0 then
 begin
   if j = 100 then
     Caption := 'Number is 100!'
   else
     Caption := 'Number is NEGATIVE!';
 end;
 
Our ELSE statement will be interpreted as a part of the "inner" IF statement. The "inner" statement is a closed statement and doesn't need a BEGIN..ELSE.

To make sure you know how your nested if statements are treated by the compiler, and to fix the above "problem", you can write the initial version as:

 j := 50;
 if j >= 0 then
   if j = 100 then Caption := 'Number is 100!' else
 else
   Caption := 'Number is NEGATIVE!';
 
Uh! The ugly "else" ends the nested if line!? Does compile, does work!

The best solution is: always use begin-end pairs with nested if statements:

 j := 50;
 if j >= 0 then
 begin
   if j = 100 then Caption := 'Number is 100!';
 end
 else
 begin
   Caption := 'Number is NEGATIVE!';
 end;
 
Too much begin-end pairs for you? Better safe than sorry! Anyway, Code Templates are designed to add commonly used skeleton structures to your source code and then fill in.

©2014 About.com. All rights reserved.