add.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /* Example of a Variadic Function
  2. Copyright (C) 1991-2019 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either version 2
  6. of the License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <stdarg.h>
  15. #include <stdio.h>
  16. int
  17. add_em_up (int count,...)
  18. {
  19. va_list ap;
  20. int i, sum;
  21. va_start (ap, count); /* Initialize the argument list. */
  22. sum = 0;
  23. for (i = 0; i < count; i++)
  24. sum += va_arg (ap, int); /* Get the next argument value. */
  25. va_end (ap); /* Clean up. */
  26. return sum;
  27. }
  28. int
  29. main (void)
  30. {
  31. /* This call prints 16. */
  32. printf ("%d\n", add_em_up (3, 5, 5, 6));
  33. /* This call prints 55. */
  34. printf ("%d\n", add_em_up (10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
  35. return 0;
  36. }