公 告

欢迎各位网友添加友情链接,在您添加本博客:http://linux0818.blogspot.com/ 做为链接后, E-mail:linux0818@gmail.com给我,我将将您的网址添加到本博客。

2008年10月14日星期二

变长参数va_start(),va_arg(),va_end()举例

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

typedef unsigned char bool;
   
#define true 1
#define false 0
#define wrtlog(fmt, args...) {fprintf(stdout, fmt, ##args);}
#define prtmsg(fmt, args...) {fprintf(stdout, fmt, ##args);wrtlog(fmt, ##args);}
   
int sumn(int a, int b, int n, ...);

void foo(char *fmt, ...);
   
int main(int argc, char **argv)
{
    bool x;
    char s[] = "hello";
    x = false;
    prtmsg("%s.1 this is:%d, another is:%d\n", s, x, !x);
    x = true;
    prtmsg("%s.2 this is:%d, another is:%d\n", s, x, !x);
    prtmsg("sum is:%d\n",
           sumn(10, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000));
    foo("scdsd", s, 'X', 100, "again", 101);
    return 0;
}
   
int sumn(int n, int a, int b, ...)
{  
    va_list ap;
    int x;
    int sum = 0;
    sum += (a + b);
    va_start(ap, b);
    while (n-- > 2) {
        x = va_arg(ap, int);
        printf("x=%d\n", x);
        sum += x;
    }
    va_end(ap);
    return sum;
}

void foo(char *fmt, ...)
{
    va_list ap;
    int d;
    char c, *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);
}


--
/**************************************/
Name: Xiong Feng
E-mail:linux0818@gmail.com
MSN:linux0818@hotmail.com
QQ:23562033
Address: GuangZhou.China
/**************************************/

没有评论:

发表评论