Search:
All Any

Part of mariaus.info network Subscribe via RSS
Follow on twitter Request a tutorial
Wallpaper: Inside the binary
Create a supernova in Photoshop
Create a stuck in the ground icon
Create a background for a space scene
Create an automated reusable software box model
Photography and art inspiration # 3
Photography and art inspiration # 1
Photography and art inspiration # 4
Photography and art inspiration # 2
Go to first pageAdd to favorites (this)Contact page ownerRequest a tutorialSubscribe to the Tip Kit news
Request a tutorial
Introduction to Delphi, Part 7 - Conditionals and logical operators

Conditional statements allow you to do some decision making in your code. Learn how it's done in this tutorial.
In a previous tutorial, we've learned the difference between procedures and methods. It is time to add some decision making to our code. Until now we could just create a program that runs from the beginning to the end, but there are sometimes situations (conditions) when we want to execute some code based on some condition or some different code if this condition is not met. Conditions can be defined in the following ways:

// the single-line way:

if CONDITION then
  some_action // note there is no semicolon before ELSE
else
  other_action;

// the multi-line way:

if CONDITION then
begin
  some_action;
  some_action_2;
end // note there is no semicolon again
else begin
  other_action;
  other_action_2;
end;
As you can see, conditional statements start with IF, followed by a condition to be met, followed by THEN. If a condition is met, then Delphi starts executing the THEN block. If you want Delphi to give a responce if the condition was not met - you need an ELSE code block. Note that there is no semicolon before the word ELSE cause it's not allowed by Delphi. If you just want to execute some code if a condition is met - you don't need to write an ELSE. Let's see the following example to make things clearer:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

// information about a person
const
  person_age = 19;
  person_gender = 'male';
  person_vegetarian = true;
  person_weight_kg = 70;
  person_name = 'John';
  person_lname = 'Doe';

type
  TForm1 = class(TForm)
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  procedure TestIf;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TestIf;
begin
  if person_age > 10 then
    ShowMessage('Person is more that 10 years old')
  else
    ShowMessage('Person is younger than 10');
end;

end.
In this example, there are some constants defined in the top of the unit, describing some person. In the TestIf procedure, with the help of conditional statements, we test if this person of ours is older that 10. If he/she is - we show a confirmation message, if not - we show another message. We could also write it like this:
procedure TestIf;
begin
  if person_age > 10 then
  begin
    ShowMessage('Person is more that 10 years old');
  end
  else
  begin
    ShowMessage('Person is younger than 10');
  end;
end;
Here we notice the BEGIN and END statements. When we want to execute a single command, we don't need them (like in this case). But if we wanted to do more coding if the condition was met/unmet - then we would need to surround our code by BEGIN .. END statements.

Conditions themselves can be whatever we want them to be. The only thing to remember is that they can only result in TRUE or FALSE. For exemple, person_age > 10 is either correct or not. We could also write (person_age / 60) * 514 < 100 + 55 and it could also result in either true or false. Now let's get more complicated. Let's say we want to show a message if the person is female and she is vegetarian. To do this, we will be needing some help from logical operators. These operators allow you to write multiple conditions and resolve them to a single true or false. For example, in our case, if the person is a vegetarian female - we have ourselves a true, but if it's not a female or a female that eats meat - we have a false. Let's look at the following example of how can this be done without any logical operators:
procedure TestIf;
begin
  if person_gender = 'female' then
    if person_vegetarian = true then
      ShowMessage('We have a vegetarian lady');
end;
Note that in conditional statements we use instead of :=. It is simple to remember when to use any of them.

use = when you need to test the equality between left and right side of the expression.
use := when you need to assign the value on the right side to the variable on the left.

So in the previous example, we first test if our person is a female and then, when the condition is met, we once again test if she is a vegetarian. Finally, if the second condition is met, we show a confirmation message. It also shows you the way to combine multiple if statements together. You can combine as many as you want. Now let's see an example with logical operators:
procedure TestIf;
begin
  if (person_gender = 'female') AND (person_vegetarian = true) then
    ShowMessage('We have a vegetarian lady');
end;
Simple, isn't it? You can already guess that AND is a logical operator. This multiple condition only results to true if BOTH conditions result in true. If any of them results in false - then the entire multiple condition returns false. So if you wrote a hundred similar conditions and at least one of them was false - the ShowMessage would not be executed.

Another logical operator is OR. This operator only needs one of the conditions to be true to make the entire multiple condition result in true. Example:
procedure TestIf;
begin
  if (person_gender = 'female') OR (person_vegetarian = true) then
    ShowMessage('We have a vegetarian, a lady or both');
end;
In this case, our person has to be either a woman or a vegetarian. So vegetarian men or meat eating women would do.

Third operator is NOT. As the name says, it checks if the condition is not what it is supposed to be. Look at the example to make things clear:
procedure TestIf;
begin
  if (person_gender = 'female') OR (NOT (person_vegetarian = true)) then
    ShowMessage('We have a non vegetarian or a lady or both');
end;
For the sake of clarity, it is best to surround each logical operation in brackets. So in this example, everyone who is a female or everyone who is not vegetarian would meet the condition. Notice that a NOT before the expression requires it to be an inverse variant of what it is supposed to be. In this case, person is supposed to be vegetarian, but we have a NOT operator, that now requires the person not to be a vegetarian. The same could be acchieved like this:
procedure TestIf;
begin
  if (person_gender = 'female') OR (person_vegetarian <> true) then
    ShowMessage('We have a non vegetarian or a lady or both');
end;
Here we've replaced the NOT part with the not equals "<>" operator.

The last operator is XOR. This one is much like the OR operator, but closer to the real life. Consider the following phrase: "To be or not to be". A very famous phrase, though it wouldn't make sense in Delphi. Why not? Because of the OR. In Delphi this operator would result in true if any of the conditions were met. That means that we could "be" and "not be" in the same time. Now isn't that a nonsense? In delphi, situations like this are handled by the XOR operator. "To be XOR not to be" would be absolutely correct, because now we can "be", we can "not be", but we can't be both at the same time. So as you've already guessed, XOR returns true if any of the conditions are met, but returns false if all of them are met. Example:
procedure TestIf;
begin
  if (person_gender = 'female') XOR (person_vegetarian = true) then
    ShowMessage('We have a vegetarian or lady but definately not both');
end;
In this case, our person could be a female or a vegetarian, but could not be both (a vegetarian female).

So hope you've learned the basics of conditional statements, because in the next tutorial, we'll be using them in more complex code. Click here to read it.

Article written by: Marius S.
This article is an intellectual property of its respective author. All images, used here are property of tip-kit.com if not stated otherwise.
Share this article
Digg del.icio.us Facebook Furl Google Reddit Slashdot StumbleUpon Technorati
How easy was it to understand? Was it useful?










Leave a reply
Your name:

Message:

Confirmation code
Please enter the above code:
There are no comments yet. You can use the above form to leave a reply.
Copyright © 2009 Tip-Kit.Com | Valid XHTML 1.0 | Powered By Isis | RSS