variable function parameters functionname(int a, ...)

Reply

Join Date: Aug 2004
Posts: 140
Reputation: chound is an unknown quantity at this point 
Solved Threads: 1
chound chound is offline Offline
Junior Poster

variable function parameters functionname(int a, ...)

 
0
  #1
Aug 28th, 2004
How do I create a function with variable parameters. Will "functionname(float a, ...);" work? If it does how do I use the variables.
Eg.

  1. void f1(int i, ...);
  2. void main()
  3. {
  4. int a, b,c;
  5. cout<<"Enter 3 values";
  6. cin>>a>>b>>c;
  7. f1(a, b, c);
  8. }
  9. void fi()
  10. {
  11. //How do I access the variables that are passed as parameters
  12. }

:cry: :lol: :rolleyes:
Reply With Quote Quick reply to this message  
Join Date: Jun 2004
Posts: 436
Reputation: Chainsaw is an unknown quantity at this point 
Solved Threads: 10
Chainsaw's Avatar
Chainsaw Chainsaw is offline Offline
Unprevaricator

Re: variable function parameters functionname(int a, ...)

 
0
  #2
Aug 28th, 2004
You need at least one real parameter, as you have in your example. Then you use some special macros to access the parameters:

  1.  
  2. void AddSomeNumbers( int howMany, .... ) // any number of 'real' params, folowed by ...
  3. {
  4. va_list argptr;
  5. int ret = 0;
  6.  
  7. va_start( argptr, howMany ); // use the last 'real' param here
  8.  
  9. for (int i = 0; i < howMany; i++)
  10. ret += va_arg( argptr, int ); // the next arg is an int, we hope
  11.  
  12. va_end(argptr);
  13.  
  14. return ret;
  15. }

The caviats are:
1) You do not know how many parameters were supplied. Thats why in my sample I had that be the one 'real' parameter.
2) You do not know the type of parameters, so you have to 'guess' and hope the caller knows what they are doing!

printf() and its variants use this, and the format string specifies the number and type of parameters:

printf( "%s %d %x\n", "string", number, number );

but if you screw up you get fun results!

printf( "%s %d %d\n", number, "string", 1.2 ); // ick!
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC