Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

function with variable number of parameters 1

Status
Not open for further replies.

Themuppeteer

Programmer
Apr 4, 2001
449
BE
Hello,

I think my teacher told me once in school that you can have a variable number of parameters in a function.

e.g.

result=add(1,5);
result=add(1,5,6);
result=add(1,5,6,9);

in 1 function. (not by using an array)

Anybody knows how to write this add function ?

Greetz,
muppeteer.gif

NOSPAM_themuppeteer@hotmail.com (for mails, remove the NOSPAM_)

Don't eat yellow snow...and don't mess with your fstab!
 
found it..

#include <iostream.h>
04: #include <stdarg.h>
05:
06: // Declare a function with one required parameter
07: void display_var(int number, ...);
08:
09: main()
10: {
11: int index = 5;
12: int one = 1, two = 2;
13:
14: display_var(one, index);
15: display_var(3, index, index + two, index + one);
16: display_var(two, 7, 3);
17: }
18:
19:
20: void display_var(int number, ...)
21: {
22: va_list param_pt;
23:
24: va_start(param_pt,number); // Call the setup macro
25:
26: cout << &quot;The parameters are &quot;;
27: for (int index = 0 ; index < number ; index ++)
28: cout << va_arg(param_pt,int) << &quot; &quot;; // Extract a parameter
29: cout << &quot;\n&quot;;
30: va_end(param_pt); // Closing macro
31: }


--------------------------------------------------------------------------------

Result of execution
The parameters are 5
The parameters are 5 7 6
The parameters are 7 3

Greetz,
muppeteer.gif

NOSPAM_themuppeteer@hotmail.com (for mails, remove the NOSPAM_)

Don't eat yellow snow...and don't mess with your fstab!
 
yes u can do that, but there are some exceptions
lets see a class circle wich contains radio, and x,y as it position.
ex: circle (int radio, int x, int y)


if u call circle (4) you'll have a circle with radio = 4 and x, y set as default (depends of your constructor)
if u call circle (10, 20)
you can set your constructor as x= 10 and y=20 and radio as default or radio 0 10 and x=20 and y as default
check the constructors help to get more about it
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top