Variadic Functions in Visual FoxPro

990 views Asked by At

How does one write a Variadic Function in Microsoft Visual Foxpro?

A variadic function is one that accepts a variable number of arguments - see http://en.m.wikipedia.org/wiki/Variadic_function. Examples are given for just about every other programming language in the world at http://rosettacode.org/wiki/Variadic_function but not the good ol' fox.

So given the following function:

Function PrintVars(var1,var2,var3)
    ? var1
    ? var2
    ? var3
End Func

How do we allow any number of arguments?

2

There are 2 answers

3
LAK On BEST ANSWER

You have a limited ability to do this in VFP.

FUNCTION printvars
PARAMETERS p1, p2, p3, p4
    ? "Parameter count", PARAMETERS()
    ? p1
    ? p2
    ? p3
    ? p4
RETURN

Call this like this: printvars(1, 2)

and your results will be:

Parameter count    2
         1
         2
.F.
.F.

VFP will initialize any parameter you don't explicitly pass with a logical .F. value. The PARAMETERS() function obviously tells you how many were actually passed.

Passing too many parameters will give you an error that your PARAMETER statement needs to specify more parameters.

3
Tamar E. Granor On

I would disagree that this is a limited capability. You don't have to do anything special. By default, VFP lets you pass fewer than the specified number of parameters.

Also, don't use the PARAMETERS() function to see how many parameters you received. It has a flaw; if you call another routine before using it, it tells you how many parameters were passed to that routine. Use PCOUNT() instead; it always tells you how many parameters were passed to the current routine.

Here's some code that demonstrates what's wrong with PARAMETERS():

DEBUG

Subproc("abc", 123)

RETURN

PROCEDURE Subproc(cParm1, nParm2)

DEBUGOUT "Immediately on entry to Subproc"
DEBUGOUT "  PARAMETERS() returns ", PARAMETERS()
DEBUGOUT "  PCOUNT() returns ", PCOUNT()

Subsubproc()

DEBUGOUT "After call to Subsubproc"
DEBUGOUT "  PARAMETERS() returns ", PARAMETERS()
DEBUGOUT "  PCOUNT() returns ", PCOUNT()

RETURN

PROCEDURE Subsubproc

RETURN

After running this code, take a look in the Debug Output window.