menu

valist

  • date_range 14/12/2020 12:20
    点击量:
    info
    sort
    c
    label
    c

文章出自个人博客https://applelin8.github.io/2020/12/14/valist,转载请申明


content


valist

如何获取函数的变长参数(va_list, va_start, va_arg, va_end) primer中讲得比较浅,提到了怎么声明怎么调用,但是没有写明在函数内部是如何获取变长参数。 1)省略号(ellipsis)

void fun1(int a, double b, …); //给出确定的几个参数,其他用省略号 void fun2(int a …) //省略号前有没有逗号都可以 void fun3(…) //也可以不确定任何参数,但与没参数是不一样的。

典型应用 printf:

int pritnf(const char *format, [, argument] …); //官方声明 printf(“My name is %s, age %d.”, “Apple”, 24); //调用

2)通用工作原理 使用步骤:

a) 定义 va_list 变量ap b) va_start 初始化ap c) va_arg返回变长参数值。 d) va_end重置ap为NULLset

example

#include <stdio.h>
#include <stdarg.h>

#define __printf(a, b)	__attribute__((format(printf, a, b)))

#if 1
#define CHECK_FMT(a, b) __attribute__((format(printf, a, b)))
#else
#define CHECK_FMT(a, b)
#endif

void TRACE(const char *fmt, ...) CHECK_FMT(1, 2);

void TRACE(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);  //va_start

    char ch;

    while(ch = *(fmt++)) //Iterate over the format string
    {
        if('%' == ch)
        {
            ch=*(fmt++);
            if(ch == 's')
            {
                char *str = va_arg(ap, char*); //va_arg
                printf("%s", str);
            }
            else if(ch == 'd')
            {
                int age = va_arg(ap, int); //va_arg
                printf("%d", age);
            }
        }
        else
        {
            printf("%c", ch);
        }
    }
    va_end(ap);
}

int main(void)
{
    TRACE("iValue = %d\n", 6);
    TRACE("iValue = %d\n", "test");

    return 0;
}


评论:


技术文章推送

手机、电脑实用软件分享

微信搜索公众号: farmer in city
wechat 微信公众号:farmer in city