boot2

Playing with the boostrap
git clone https://git.ryansepassi.com/git/boot2.git
Log | Files | Refs | README

067-vararg-call.c (926B)


      1 /* §G.1 — variadic call: caller default-promotes args.
      2  *
      3  * Declares sum3 as (int n, ...) and defines it as a real variadic fn
      4  * pulling its tail args via va_arg. Calls sum3(1, c, s)
      5  * where c is signed char = -3 and s is short = 100. Per default-
      6  * promote rules, c and s widen to int before the call, so the
      7  * receive yields full 32-bit -3 and 100.
      8  *
      9  * Result: 1 + (-3) + 100 = 98.
     10  */
     11 
     12 #ifndef CCSCM
     13 #include <stdarg.h>
     14 #else
     15 typedef char *va_list;
     16 #define va_start(ap, n) __builtin_va_start(ap, n)
     17 #define va_arg(ap, t)   __builtin_va_arg(ap, t)
     18 #define va_end(ap)      __builtin_va_end(ap)
     19 #endif
     20 
     21 int sum3(int n, ...);
     22 
     23 int main(void) {
     24     signed char c; short s;
     25     c = -3; s = 100;
     26     return sum3(1, c, s);  /* 1 + (-3) + 100 = 98 */
     27 }
     28 
     29 int sum3(int n, ...) {
     30     va_list ap;
     31     int a; int b;
     32     va_start(ap, n);
     33     a = va_arg(ap, int);
     34     b = va_arg(ap, int);
     35     va_end(ap);
     36     return n + a + b;
     37 }