943,685 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 6354
  • C RSS
Aug 28th, 2004
0

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

Expand Post »
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:
Similar Threads
Reputation Points: 15
Solved Threads: 1
Junior Poster
chound is offline Offline
143 posts
since Aug 2004
Aug 28th, 2004
0

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

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!
Reputation Points: 36
Solved Threads: 11
Posting Pro in Training
Chainsaw is offline Offline
436 posts
since Jun 2004

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: reading and printing a file to screen in C
Next Thread in C Forum Timeline: Help in Input output C files





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC