How can I access the local variable of a routine from outside. Like this one eg
procedure TForm1.CalculateTax(var Amount: Double);
var
Tax : Double;
begin
Tax := Amount*2.5/100;
end;
You can't access a local variable from outside the procedure it's declared in.
The best solution is to change your procedure
to a function
, and have it return the value.
Change your TForm1
declaration
type
TForm1 = class(TForm)
...
procedure CalculateTax(var Amount: Double);
to
type
TForm1 = class(TForm)
...
function CalculateTax(const Amount: Double): Double;
Change the implementation from
procedure TForm1.CalculateTax(var Amount: Double);
var
Tax : Double;
begin
Tax := Amount*2.5/100;
end;
to
function TForm1.CalculateTax(const Amount: Double): Double;
begin
Result := Amount*2.5/100;
end;
Call it like this:
Tax := CalculateTax(YourAmount);
My $0.02:
1) I would make this a "function" rather than a "procedure" (because it's purpose is to "return a value" - the tax amount)
2) I would not hard-code either the "amount" or "tax rate" inside the routine
3) I would not "overload" (give multiple meanings to) the variable "amount"
// Better
function TForm1.CalculateTax(purchaseAmount, taxRate: Currency) : Currency;
begin
Result := purchaseAmount * (taxRate / 100.0);
end;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.