Changes between Version 1 and Version 2 of Arrays
- Timestamp:
- 09/14/13 09:54:37 (13 years ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
Arrays
v1 v2 1 1 = Arrays = 2 2 3 Thoughts on arrays and related issues. 3 C uses an "array-pointer" pun. This is not a particularly useful feature and leads to a lot of confusion. In C, code such as 4 4 5 * drop C's silly pointer-array pun. Pointers and arrays have nothing to do with each other. In C,6 5 {{{ 7 6 void f(double[] x) {…} … … 19 18 … 20 19 }}} 21 In CIVL-C (CIVL?), you write the one you mean.22 20 23 * Arrays are values just like any other kind of value (similar to structs). They can be passed as arguments to functions and returned by functions.21 Moreover, in C there is no way to pass an array value as an argument to a function, or return an array value, or assign an array value to a variable of array type, all features we would like to include in CIVL-C. 24 22 25 * The incomplete array type "array of t", denoted `t[]`, can be used (almost) anywhere a type is expected, including the element type of an array type. The domain of `t[]` is all arrays of `t`, of any length. A complete type `t[n]` is a subtype of `t[]`. Example: 23 CIVL-C maintains backwards compatibility with C. To enable the new features above, a new type of declaration of variables of array type is introduced, using double brackets instead of single brackets. Both forms declare the same type (array of T), but variables declared with double brackets will not have the automatic conversions to pointers applied to them. The double-bracket objects can also be passed as parameters in function calls (without conversion), assigned, and returned by functions. For example: 24 26 25 {{{ 27 $message[] append_message($message[] queue, $message m); 26 int[[]] double(int a[[]], int n) { 27 int b[[n]]; 28 29 for (int i=0; i<n; i++) 30 b[i] = 2*a[i]; 31 return b; 32 } 33 34 void main() { 35 int x[[5]], y[[]]; 36 37 for (int i=0; i<5; i++) 38 x[i] = i; 39 y = double(x); 40 } 41 }}} 42 43 is a legal CIVL-C program and at termination y hold the array value {0,2,4,6,8}. Note no pointers are ever used in this program. 44 45 Another example: 46 {{{ 47 $message[[]] append_message($message[[]] queue, $message m); 28 48 }}} 29 49 takes an array of messages and returns an array one longer which is equivalent to the original array with $m$ added. There is no "sharing" between these two arrays. 30 50 51 You can still modify double-bracketed arrays and create references to elements of them, just as with regular arrays: 52 {{{ 53 void f(int a[[]], int n) { 54 a[0] = 10; 55 56 } 57 }}} 58 59 == Other related ideas == 60 31 61 * Instead of malloc, introduce an operator `$alloc(heap, type)` where `heap` is an expression of type pointer-to-heap and `type` is a type name. The type of this expression is pointer-to-`type`. It allocates an object of the given type on the specified heap and returns a pointer to that object.
