Jump to content

[PASCAL] Constants


CouldnoT
 Share

Recommended Posts

Constants

 

Constants are similar to variables. They have names and can hold values, but differ from variables in modifying that value. Constant values can not be modified while running the application, and their values should be determined before compiling the application. We have used constants in a different way before, without naming them,

 

just as an Integer value or string as in this example:

 

Writeln(5);
 Writeln('Hello');

 

The value 5 will never change after running the application. 'Hello' is also a string constant. We can define constants using the Const keyword after the application's uses

 

clause as in the following example:

 

Fuel Consumption program: 

program FuelConsumption;
{$mode objfpc}{$H+}
uses
 {$IFDEF UNIX}{$IFDEF UseCThreads}
 cthreads,
 {$ENDIF}{$ENDIF}
 Classes, SysUtils
 { you can add units after this };
const GallonPrice = 6.5;
var
 Payment: Integer;
 Consumption: Integer;
 Kilos: Single;
begin
 Write('How much did you pay for your car''s fuel: ');
 Readln(Payment);
 Write('What is the consumption of your car? (Kilos per Gallon): ');
 Readln(Consumption);
 Kilos:= (Payment / GallonPrice) * Consumption;
 Writeln('This fuel will keep your car running for : ',
 Format('%0.1f', [Kilos]), ' Kilometers');
 Write('Press enter');
 Readln;
end.

 

In the previous example, we will calculate the kilometers that the car could run with its current fuel according to these facts:

 

1. Car fuel consumption: we have used the Consumption variable to store kilometers per gallon for the current car
2. Fuel: we have used the Payment variable to store how much money we paid for the current fuel
3. Gallon Price: we have used the GallonPrice constant to store the price for a gallon of fuel for the current country. This value shouldn't be entered by the user; instead, it should be defined by the programmer.


Constants are recommended when using the same value many times in the application. If we need to change this value, we can do it once at the header of code.

 

PS

Format replaces all placeholders inFmt with the arguments passed in Args and returns the resulting string. A placeholder looks as follows:

'%' [[Index]':'] ['-'] [Width] ['.' Precision] ArgType

 

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.