Tuesday, November 10, 2009

Logical error

Yesterday a friend of mine asked me something this:

Facts:
- you have 3 units, u1, u2 and u3.
- u1 is the main unit which contains main form with a button called Button1.
- u2 contains a global function called Sum declared as
function Sum(a, b: integer): integer:
begin
     Result := a + b;
end;
- u3 also contains a global function called Sum declared as
function Sum(a, b: integer): integer:
begin
     Result := a * b;
end;
- u1(the main unit) has u2 and u3 in uses clause and on Button1's OnClick event has the fallowing code
...
begin
     ShowMessage('Result = ' + IntToStr(Sum(3, 3)));
end;

Question: What would be the result of using Sum function with 3 as first parameter and 3 as second parameter?
I know you tend to say 6 as result but Delphi says NO! This is a so called logical error because if you have two units which both have a function called Sum(in this case) Delphi will use Sum function from last unit added in uses clause.
You don't bulive me? then test it yourself, here's the code

unit1.pas
unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses unit2, unit3;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
     ShowMessage('Result = ' + IntToStr(Sum(3, 3)));
end;

end.

unit2.pas
unit Unit2;

interface

function sum(a, b: integer): integer;

implementation

function sum(a, b: integer): integer;
begin
     Result := a + b;
end;

end.

unit3.pas
unit Unit3;

interface

function sum(a, b: integer): integer;

implementation

function sum(a, b: integer): integer;
begin
     Result := a * b;
end;

end.

No comments:

Post a Comment

Blogroll(General programming and Delphi feeds)