Jump to content

Multiple distinct objects: Difference between revisions

→‎{{header|Modula-3}}: added the mistake
(→‎{{header|Modula-3}}: a much more thorough example that clearly initializes its values)
(→‎{{header|Modula-3}}: added the mistake)
Line 824:
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.
 
Modula-3 offers reference and pointer types, so the mistaken way of initializing is quite easy to do for the careless.
The example program below demonstrates each of these three methods, and so is a bit long.
 
The example program below demonstrates each of these three methods, andincluding the mistaken way, so is a bit long.
<lang modula3>MODULE DistinctObjects EXPORTS Main;
 
Line 847 ⟶ 849:
t2 := T { 4 };
t3 : T; (* t3's value will be default (2) *)
 
(* initialize a reference to T with value 100 *)
tr := NEW(REF T, value := 100);
 
(* initialize an array of records *)
Line 852 ⟶ 857:
(* initialize an array of integers *)
b := ARRAY[1..Size] OF INTEGER { -9, 2, 6 };
(* initialize an array of references to a record -- NOT copied! *)
c := ARRAY[1..Size] OF REF T { tr, tr, tr };
 
BEGIN
Line 858 ⟶ 865:
FOR i := 1 TO Size DO
IO.PutInt(a[i].value); IO.Put(" , ");
IO.PutInt(b[i]); IO.Put(" ;, ");
IO.PutInt(c[i].value); IO.Put(" ; ");
END;
IO.PutChar('\n');
Line 864 ⟶ 872:
(* re-initialize a's data to random integers *)
FOR i := 1 TO Size DO a[i].value := random.integer(-10, 10); END;
(* modify "one" element of c *)
c[1].value := 0;
(* display the data *)
FOR i := 1 TO Size DO
IO.PutInt(a[i].value); IO.Put(" , ");
IO.PutInt(b[i]); IO.Put(" ;, ");
IO.PutInt(c[i].value); IO.Put(" ; ");
END;
IO.PutChar('\n');
Line 873 ⟶ 884:
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. On the other hand, the modification of "one" element of <code>c</code> actually modifies every element, precisely because it is a reference and not an object.
<pre>
3 , -9 , 100 ; 4 , 2 , 100 ; 2 , 6 , 100 ;
3-1 , -9 , 0 ; -89 , 2 , 0 ; 78 , 6 , 0 ;
</pre>
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.