Anonymous user
Multiple distinct objects: Difference between revisions
→{{header|Modula-3}}: a much more thorough example that clearly initializes its values
No edit summary |
(→{{header|Modula-3}}: a much more thorough example that clearly initializes its values) |
||
Line 820:
=={{header|Modula-3}}==
Similar to the [[Ada]] version above:
<lang modula3>VAR a: ARRAY[1..N] OF T</lang>
This creates an array of distinct elements of type <code>T</code>. A type may specify a default value for its fields, so long as the values are compile-time constants. Similarly, an array can initialize its entries to multiple different values, also compile-time constants. Naturally, a program may initialize this data at run-time using a <code>FOR</code> loop.
The example program below demonstrates each of these three methods, and so is a bit long.
<lang modula3>MODULE DistinctObjects EXPORTS Main;
IMPORT IO, Random;
VAR
random := NEW(Random.Default).init();
TYPE
T = RECORD (* value will initialize to 2 unless otherwise specified *)
value: INTEGER := 2;
END;
CONST Size = 3;
VAR
(* initialize records *)
t1 := T { 3 };
t2 := T { 4 };
t3 : T; (* t3's value will be default (2) *)
(* initialize an array of records *)
a := ARRAY[1..Size] OF T { t1, t2, t3 };
(* initialize an array of integers *)
b := ARRAY[1..Size] OF INTEGER { -9, 2, 6 };
BEGIN
(* display the data *)
FOR i := 1 TO Size DO
IO.PutInt(a[i].value); IO.Put(" , ");
IO.PutInt(b[i]); IO.Put(" ; ");
END;
IO.PutChar('\n');
(* re-initialize a's data to random integers *)
FOR i := 1 TO Size DO a[i].value := random.integer(-10, 10); END;
(* display the data *)
FOR i := 1 TO Size DO
IO.PutInt(a[i].value); IO.Put(" , ");
IO.PutInt(b[i]); IO.Put(" ; ");
END;
IO.PutChar('\n');
END DistinctObjects.</lang>
{{out}}
Each line interleaves the initial values of <code>a</code> and <code>b</code>. The first one has default values; the second replaces the values of <code>a</code> with random, "re-initialized" integers. Only <code>a[3]</code> starts with the default value for <code>T</code>; see the fifth number in the first line.
<pre>
3 , -9 ; 4 , 2 ; 2 , 6 ;
3 , -9 ; -8 , 2 ; 7 , 6 ;
</pre>
=={{header|NGS}}==
|