DMarlon Studio

Lesson 14 · 14 of 20

Functions and Result · Pascal

Write Pascal functions that return a value through Result: Celsius to Fahrenheit, prices with VAT and whether a year is a leap year.

Pascal · Functions and Result in DMarlon Studio: the example's code and its output in the terminal

A function is like a procedure, but it returns a value. It is declared with `function`, its parameters and, after the colon, the type of the result: function CelsiusToF(c: Double): Double.

The value is returned through the special variable `Result`: whatever it holds when the function ends is what the caller gets. You can assign it several times and read it inside the function, like any other variable.

WithVat has a local constant, Rate, set to 21 %. IsLeap returns a Boolean with the full leap-year rule: divisible by 4 but not by 100, or divisible by 400. That is why 1900 is not a leap year and 2000 is.

A function call goes wherever a value could go: inside WriteLn, in a sum such as 2 * WithVat(20), or followed by the :5:1 format. In the for loop, CelsiusToF(temp * 10) converts 0, 10, 20 and 30 degrees.

You can also assign the result to the function's name (CelsiusToF := ...), as in classic Pascal, but Result is clearer and is the norm in Free Pascal (objfpc mode) and Delphi.

Code · main.pas

program main;// A function returns a value: whatever is left in Result.function CelsiusToF(c: Double): Double;begin  Result := c * 9 / 5 + 32;end;function WithVat(price: Double): Double;const  Rate = 0.21;begin  Result := price * (1 + Rate);end;function IsLeap(year: Integer): Boolean;begin  Result := ((year mod 4 = 0) and (year mod 100 <> 0)) or (year mod 400 = 0);end;var  temp: Integer;begin  // A function call goes wherever a value can go.  for temp := 0 to 3 do    WriteLn(temp * 10:3, ' C = ', CelsiusToF(temp * 10):5:1, ' F');  WriteLn('A 20-euro shirt with VAT: ', WithVat(20):0:2);  WriteLn('Two shirts: ', 2 * WithVat(20):0:2);  WriteLn('2024 is a leap year? ', IsLeap(2024));  WriteLn('1900 is a leap year? ', IsLeap(1900));  WriteLn('2000 is a leap year? ', IsLeap(2000));end.

Output · fpc main.pas && ./main

  0 C =  32.0 F
 10 C =  50.0 F
 20 C =  68.0 F
 30 C =  86.0 F
A 20-euro shirt with VAT: 24.20
Two shirts: 48.40
2024 is a leap year? TRUE
1900 is a leap year? FALSE
2000 is a leap year? TRUE

Key points

  • function Name(parameters): Type; declares a function.
  • Whatever is left in Result is the returned value.
  • A function is used inside expressions, like a value.
  • Functions can have their own constants and variables.

Exercise

Write a Discount(price: Double; percent: Integer): Double function that returns the reduced price, and use it to print the price of a 20-euro T-shirt with a 15 % discount and VAT.