kit

kit
git clone https://git.ryansepassi.com/git/kit.git
Log | Files | Refs | README

variadic_07_nested_call.c (874B)


      1 /* va_copy lets a caller make a second walk of the same arg list — here
      2  * we use it to call a helper from inside the variadic function while
      3  * preserving the original cursor for additional consumption. */
      4 int sum_n(int n, __builtin_va_list* ap) {
      5   int s = 0;
      6   for (int i = 0; i < n; i++) s += __builtin_va_arg(*ap, int);
      7   return s;
      8 }
      9 
     10 int outer(int n, ...) {
     11   __builtin_va_list ap, ap_for_helper;
     12   __builtin_va_start(ap, n);
     13   __builtin_va_copy(ap_for_helper, ap);
     14   int helper_total = sum_n(n, &ap_for_helper);
     15   __builtin_va_end(ap_for_helper);
     16   int local_total = 0;
     17   for (int i = 0; i < n; i++) local_total += __builtin_va_arg(ap, int);
     18   __builtin_va_end(ap);
     19   return helper_total + local_total - 42;
     20 }
     21 
     22 int test_main(void) {
     23   /* helper sums to 21, local sums to 21, +21+21-42 = 0 → return 42 via
     24    * the +42 below. */
     25   return outer(3, 5, 7, 9) + 42;
     26 }