JavaScriptを有効にしてください

stdarg.h

 ·  ☕ 1 min read

#Computer
#C

#** va_〇〇

1
2
3
4
++void va_start(va_list ap, last);
type va_arg(va_list ap, type);
void va_end(va_list ap);
void va_copy(va_list dest, va_list src);  
  • va_list は ただのchar *
1
typedef char* va_list
1
printf( "%d %f %s\n", 123, 4.56, "test");

→ va_list = int(4bytes) | float(8bytes) | char*(4bytes)
→ va_startはポインタをva_listの先頭に設定.
→ va_argはtypeで指定された型分ポインタをずらしていくだけ

#** usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
++#include <stdio.h>
#include <stdarg.h>

void foo(char *fmt, ...) { /* '...' is C syntax for a variadic function */
    va_list ap;
    int d;
    char c;
    char *s;

    va_start(ap, fmt);
    while (*fmt)
        switch (*fmt++) {
        case 's':              /* string */
            s = va_arg(ap, char *);
            printf("string %s\n", s);
            break;
        case 'd':              /* int */
            d = va_arg(ap, int);
            printf("int %d\n", d);
            break;
        case 'c':              /* char */
            /* need a cast here since va_arg only
               takes fully promoted types */
            c = (char) va_arg(ap, int);
            printf("char %c\n", c);
            break;
        }
    va_end(ap);
}  

引用: https://linuxjm.osdn.jp/html/LDP_man-pages/man3/stdarg.3.html

#** printfのラップ

  • printf等をラップするにはvprintf等を使う
    → v〇〇はva_listを渡すことができる
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
++void print(const char *format, ...) {
  printf(format); // warning: Format string is not a string literal (potentially insecure)
}

void print(const char *format, ...) {
  va_list ap;
  va_start(ap, format);
  vprintf(format, ap);
  va_end(ap);
}

print("%s %d", "test", 123);  // test123
共有

YuWd (Yuiga Wada)
著者
YuWd (Yuiga Wada)
機械学習・競プロ・iOS・Web