Array Of Const

An interesting feature in modern pascal languages is the ability to pass in an array of several types into a function.

This pattern can be used in other languages... the CeeLanguage for example has a varargs ability to pass in several parameters.

In ModernPascal it looks as follows:

  procedure test(a: array of const);
  var i: integer; 
  begin
    for i:= low(a) to high(a) do begin
      case a[i].vtype of
        vtAnsiString : writeln('this param is a string: ', ansistring(a[i].vAnsistring));
        vtInteger    : writeln('this param is a integer: ', a[i].vInteger);      
        vtBoolean    : writeln('this param is a boolean: ', a[i].vBoolean);            
        // ...etc
      end;    
    end;
  end;

This is how to make use of it:

  begin
    test([true, 12345, 'some string']);
  end.

(And in a nice terser form:)

  pro test(a: ray of const);
  v i: int; 
  b for i = low(a) to high(a) do b
      case a[i].vtype of
        vtAstr : outln('a string: ',   astr(a[i].vAstr));
        vtInt  : outln('an integer: ', a[i].vInt);      
        vtBool : outln('a boolean: ',  a[i].vBool);            
        // ...etc
      e;    
    e;
  e;

In use:
  b
    test([true, 12345, 'some string']);
  e.


Why it is called an array of const?

The const most likely stems from the fact that you cannot modify the values inside the function (read only), i.e. they act like read only parameters once inside the code block that is accessing this array. It does not, however, mean that you must pass only constants into the function. Similarly, const means read only for single parameters in modern pascal also, as opposed to by reference which are labeled with var prefix, or by value which are prefixed with nothing.


See also IncludeFileParametricPolymorphism where you do not have to use a CASE statement to handle the types, nor does it require an array or any casts.


EditText of this page (last edited May 23, 2008) or FindPage with title or text search