Variadic function: Difference between revisions
Content added Content deleted
MaiconSoft (talk | contribs) m (Added Delphi reference to Free Pascal code) |
Not a robot (talk | contribs) (Add BCPL) |
||
Line 599: | Line 599: | ||
for (i = 1; i <= a[0]; i++) a[i] |
for (i = 1; i <= a[0]; i++) a[i] |
||
}</lang> |
}</lang> |
||
=={{header|BCPL}}== |
|||
BCPL does not have true variadic functions, however, it is explicitly legal |
|||
to pass a function the "wrong" amount of arguments. If fewer arguments are passed |
|||
than declared, the rest will remain uninitialized, if too many are passed, |
|||
the excess arguments are ignored. Additionally, it is guaranteed that the arguments will be located sequentially |
|||
in memory, starting from the first, making it possible to treat the address of the |
|||
first argument as if it is in fact an array of arguments. |
|||
These two facts together make it easy to declare a "variadic" function by |
|||
simply specifying a whole bunch of dummy arguments in the declaration, and then calling |
|||
the function later on with however many you happen to need. At least as many arguments as |
|||
you declare are guaranteed to make it through, though any more will not necessarily. |
|||
This technique is used in the standard library (this is how <code>writef</code>, the |
|||
equivalent to C's <code>printf</code>, is defined), and the book <cite>BCPL: The Language |
|||
and its Compiler</cite> by BCPL designer Martin Richards (which is as official as it gets) |
|||
explicitly introduces this technique. |
|||
<lang bcpl>get "libhdr" |
|||
// A, B, C, etc are dummy arguments. If more are needed, more can be added. |
|||
// Eventually you will run into the compiler limit. |
|||
let foo(num, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O) be |
|||
// The arguments can be indexed starting from the first one. |
|||
for i=1 to num do writef("%S*N", (@num)!i) |
|||
// You can pass as many arguments as you want. The declaration above guarantees |
|||
// that at least the first 16 arguments (including the number) will be available, |
|||
// but you certainly needn't use them all. |
|||
let start() be |
|||
foo(5, "Mary", "had", "a", "little", "lamb")</lang> |
|||
{{out}} |
|||
<pre>Mary |
|||
had |
|||
a |
|||
little |
|||
lamb</pre> |
|||
=={{header|C}}== |
=={{header|C}}== |