fork(1) download
  1. #include<stdio.h>
  2. #include <stdarg.h>
  3.  
  4. /* The sum() function can accept variable number of arguments.
  5.   In the function declaration ... means that the number and
  6.   type of the arguments may vary. The marker ... can only
  7.   appear at the end.
  8. */
  9. int sum(int num_of_arguments, ... )
  10. {
  11. /* A list to store the aruements. In example, this may contain
  12.   1,2,3 and 4 elements on successive calls from main()
  13.   */
  14. va_list args;
  15. int sum= 0, i;
  16.  
  17. /* Directing the va_list args initialized above to start storing
  18.   all parameters folloowing the first parameter 'num_of_arguments'
  19.   */
  20. va_start (args, num_of_arguments );
  21.  
  22. va_list args_copy; //initialize a copy of va_list to be used
  23. va_copy(args_copy, args); //copy args to args_copy
  24.  
  25. for (i= 0; i< num_of_arguments; i++ )
  26. /* We add 5 to each element in variable argument list and
  27.   print it.
  28.   */
  29. printf("%d ", va_arg (args_copy, int) + 5);
  30.  
  31. va_end(args_copy); //destruct args_copy
  32.  
  33. printf("\n");
  34.  
  35. /**** Next, we use args as in previous post ****/
  36.  
  37. /* Loop until all parameters are seen. */
  38. for (i= 0; i< num_of_arguments; i++ )
  39. /* Extract the next value in argument list and add it to sum. */
  40. sum += va_arg (args,int);
  41.  
  42. /* Signal that we are done with our usage of the list */
  43. va_end (args);
  44.  
  45. return sum; /* Returns the calculated sum.*/
  46. }
  47. int main()
  48. {
  49. int result;
  50.  
  51. result=sum (4,1,2,3,4);
  52. printf("result of sum() with 5 arguement: %d \n", result);
  53.  
  54. return 0;
  55. }
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
6  7  8  9  
result of sum() with 5 arguement: 10