Declare an array

From CodeCodex

Revision as of 22:51, 1 August 2006 by Jdh30 (Talk | contribs)

This task should distinguish between languages that only allow array literals when declaring arrays (e.g. C, C++, Java) and languages that allow array literals to be arbitrary expressions (e.g. OCaml, Lisp).



One dimension

String[] oneDimension;


String[] oneDimension[];


String oneDimension[];

Populating an array with values upon declaration:

String[] oneDimension = { "a","b","c" };

Two dimension

String[][] twoDimension;


String[][] twoDimension[][];


String twoDimension[][];

Populating an array with values upon declaration:

String[][] twoDimension = { {"1","2","3"}, {"4","5","6"}, {"7","8","9"} };


* #(1 2 3)

#(1 2 3)


No need for type declarations in OCaml, thanks to type inference. OCaml has homogeneous arrays and provides array literals. For example:

# [|1; 2; 3|];;
- : int array = [|1; 2; 3|]

Note that array literals improve upon C-style (e.g. C++ and Java) array declarations because OCaml's array literals can be used anywhere (they are expressions) whereas the C-style is only valid on the right-hand side of an array declaration. For example, you can apply an array literal as a function argument directly in OCaml:

# Array.fold_left ( + ) 0 [|1; 2; 3|];;
- : int = 6

Visual Basic (3-6)

One Dimensional

Fixed Length Array:

Dim Variable(5) as string

Variable Length Array:

Dim Variable() as string

Two Dimensional

Fixed by Fixed Length Array:

Dim Variable(5,2) as string

Fixed by Variable Length Array:

Dim Variable(5,) as string

Variable by Variable Length Array:

Dim Variable(,) as string