Sunday, March 15, 2020
The Traps of the If-Then-Else Statement in Delphi Code
The Traps of the If-Then-Else Statement in Delphi Code 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 this: 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). Example of a Nested If-Then-Else Statement Lets 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 thenif 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 thenbegin à à 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 doesnt need a BEGIN..ELSE. How to Fix 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! elseelse à à 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 thenbegin à à if j 100 then Caption : Number is 100!;endelsebegin à à 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. Article submitted by Marcus Junglas
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.