1
0

varargs.c 809 B

1234567891011121314151617181920212223242526272829303132
  1. //varargs.c -- use variable number of arguments
  2. #include <stdio.h>
  3. #include <stdarg.h>
  4. double sum(int, ...);
  5. int main(void)
  6. {
  7. double s,t;
  8. s = sum(3, 1.1, 2.5, 13.3);
  9. t = sum(6, 1.1, 2.1, 13.1, 4.1, 5.1, 6.1);
  10. printf("return value for "
  11. "sum(3, 1.1, 2.5, 13.3): %g\n", s);
  12. printf("return value for "
  13. "sum(6, 1.1, 2.1, 13.1, 4.1, 5.1, 6.1): %g\n", t);
  14. return 0;
  15. }
  16. double sum(int lim,...)
  17. {
  18. va_list ap; // declare object to hold arguments
  19. double tot = 0;
  20. int i;
  21. va_start(ap, lim); // initialize ap to argument list
  22. for (i = 0; i < lim; i++)
  23. tot += va_arg(ap, double); // access each item in argument list
  24. va_end(ap); // clean up
  25. return tot;
  26. }