Unspecified number of parameters for a function?
Author |
Message |
Naveg
|
Posted: Wed Oct 12, 2005 4:04 pm Post subject: Unspecified number of parameters for a function? |
|
|
Are there any languages that support an unspecified number of parameters for a method? For all I know it may be a concept that exists in every language that I just have not yet reached in my studies. Take for example method lowestCommonMultiple which, as the name suggests, finds the lowest common multiple of given numbers. Now, it would be typical to set the parameters of this method as (int firstNumber, int secondNumber) - at my level anyhow - but what if one wished to find the LCM of more than 2 numbers (ie. an unspecified number of arguments)? Is there a way to do this?
I am sure this is possible, and I have a feeling it has to do with concepts I haven't gotten to yet, like recursion, but I'm not sure. If someone could clear this up I would appreciate it. |
|
|
|
|
![](images/spacer.gif) |
Sponsor Sponsor
![Sponsor Sponsor](templates/subSilver/images/ranks/stars_rank5.gif)
|
|
![](images/spacer.gif) |
wtd
|
Posted: Wed Oct 12, 2005 4:09 pm Post subject: (No subject) |
|
|
Perl, Python, and Ruby handle this with remarkable ease.
Ruby: | def lowest_common_multiple(*numbers)
# code here
end
puts lowest_common_multiple(1, 4, 6, 3, 9, 8, 21, 53) |
|
|
|
|
|
![](images/spacer.gif) |
Naveg
|
Posted: Wed Oct 12, 2005 4:11 pm Post subject: (No subject) |
|
|
And what of a language like - your favourite - Java? Or C++ if you'd prefer. Is there any relatively easy way to do this is such languages? |
|
|
|
|
![](images/spacer.gif) |
wtd
|
Posted: Wed Oct 12, 2005 4:18 pm Post subject: (No subject) |
|
|
If you're using Java 1.5.0 it is possible. A quick example:
Java: | public class Test
{
public static void main (String[] args )
{
printAll (1, 2, 3, 4);
}
static void printAll (int ... numbers)
{
for (int x : numbers )
{
System. out. println(x );
}
}
} |
Give me a few minutes to whip up the equivalent C++ code. |
|
|
|
|
![](images/spacer.gif) |
wtd
|
Posted: Wed Oct 12, 2005 4:31 pm Post subject: (No subject) |
|
|
c++: | #include <cstdarg>
#include <iostream>
void print_all(int num, ...)
{
va_list ap;
va_start(ap, num);
int arg;
while (num--)
{
arg = va_arg(ap, int);
std::cout << arg << std::endl;
}
va_end(ap);
}
int main()
{
print_all(3, 2, 3, 4);
} |
|
|
|
|
|
![](images/spacer.gif) |
Monstrosity_
|
Posted: Wed Oct 12, 2005 5:06 pm Post subject: (No subject) |
|
|
C and VB also allow you to do this. |
|
|
|
|
![](images/spacer.gif) |
wtd
|
Posted: Wed Oct 12, 2005 5:11 pm Post subject: (No subject) |
|
|
"cstdarg" in C++ is simply a wrapper for "stdarg.h", which contains the same macros which work in the exact same manner. |
|
|
|
|
![](images/spacer.gif) |
|
|