Reputation: 283
In Java we can initialize an array using following code:
data[10] = {10,20,30,40,50,60,71,80,90,91};
How can we do this in Pascal?
Upvotes: 6
Views: 14675
Reputation: 343
Here’s a full example program that compiles for both Windows and Linux.
program test;
var
data: array[0..9] of integer = (10,20,30,40,50,60,71,80,90,91);
begin
writeln('Hello World');
writeln(data[0]);
end.
Upvotes: 10
Reputation: 1556
Technically initialization means the first definition (the first :=
assignment) of a variable, i. e. a transition from the state undefined to defined.
Considering your Java code example this answer focuses on a combined declaration/definition.
In Extended Pascal as laid out by the ISO standard 10206 a variable declaration may be followed by an initial value specification. It looks like this:
program arrayInitializationDemo;
var
data: array[1..10] of integer value [ 1: 10; 2: 20; 3: 30;
4: 40; 5: 50; 6: 60; 7: 71; 8: 80; 9: 90; 10: 91];
begin
end.
Furthermore, you can omit one recurring value with an array completer clause:
data: array[1..10] of Boolean value [1, 4..6: true; otherwise false];
Now data[1]
, data[4]
, data[5]
and data[6]
are true
, any other component of data
is false
.
And certainly you can nest arrays.
Extended Pascal has the really neat feature of associating an initial value specification with the data type. This relieves you from repeating yourself.
program initialStateDemo(output);
type
natural = 1..maxInt value 1;
var
N: natural;
begin
writeLn(N) { prints `1` }
end.
This can of course be overridden with a confliciting value
clause in the var
declaration.
The original Pascal as presented by Niklaus Wirth in The Programming Language Pascal – Revised Report of July 1973 did not provide any means to initialize an array
at its declaration site.
Various implementers added their own (mutually incompatible) extensions;
this list does in no way claim to be exhaustive.
In some Pascal dialects – including Delphi and FreePascal – only the method showcased by Michael works.
As far as I know, the Borland Pascal array initializer does not provide a means to simulate Extended Pascal’s otherwise
or repeat the same value for various indices (1, 4..6
in the example above);
you need to spell things out.
Turbo Pascal does not support initialized variables at all.
For Michael’s example code to work you need to substitute var
with const
.
However, this turns data
into a persistent variable, a variable that has an indefinite lifetime (i. e. is initialized only once).
VAX Pascal does support initialized variables, yet only for data types you can specify literal values for;
unfortunately in VAX Pascal you cannot specify array
literals.
Note, instead of Extended Pascal’s keyword value
VAX Pascal re‑uses :=
.
PascalABC.NET uses :=
, too, and supports abbreviated initialization for both “static arrays” and “dynamic arrays”.
var
data: array of integer := (10, 20, 30, 40, 50, 60, 71, 80, 90, 91);
Upvotes: 0