Mega Code Archive

 
Categories / Delphi / Examples
 

Variable number of arguments

Title: Variable number of arguments Question: In some situations, it can prove to be useful and convient to have a function that can accept X number of parameters. For example: At point A you'll write a function to add 3 integers together, and of course it'll only accept three parameters. At point B, you'll need an identical function, but which can accept 10 integers. So instead of doing the typical 1 + 2 + 3 + 4 etc. (this can very tedious to do, especially with more than let's say 15 numbers), you'll make a function that can accept as many (or as few) arguements as you'll ever need. Following is an example of a function that accepts N number of arguements, adds the passed numbers together and returns the result. Answer: function AddNumbers( const ArgsList : array of const ) : Integer; var ArgsListTyped: array[0..$FFF0 div SizeOf(TVarRec)] of TVarRec absolute ArgsList; n: Integer; begin result := 0; for n := Low( ArgsList ) to High( ArgsList ) do begin with ArgsListTyped[ n ] do begin case VType of vtInteger: result := result + VInteger; end; end; end; end; // AddNumbers() will return the sum of all the integers passed to it { AddNumbers( [1, 2, 3] ); will return 6 AddNumbers( [4, 5, 6, 7, 8, 9, 10, 11] ); will return 60 } { Following code was suggested by Luis Ortega. Thanks Luis! } function AddNumbers( const ArgsList : array of Integer ) : Integer; var n: Integer; begin result := 0; for n := Low( ArgsList ) to High( ArgsList ) do result := result + ArgsList[n]; end;