Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

c - How does printf handle its arguments?

How does printf handle its arguments? I know that in C# I can use params keyword to do something similar but I can't get it done in C ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Such a function is called a variadic function. You may declare one in C using ..., like so:

int f(int, ... );

You may then use va_start, va_arg, and va_end to work with the argument list. Here is an example:

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

void f(void);

main(){
        f();
}

int maxof(int n_args, ...){
        register int i;
        int max, a;
        va_list ap;

        va_start(ap, n_args);
        max = va_arg(ap, int);
        for(i = 2; i <= n_args; i++) {
            if((a = va_arg(ap, int)) > max)
                max = a;
        }

        va_end(ap);
        return max;
}

void f(void) {
        int i = 5;
        int j[256];
        j[42] = 24;
        printf("%d
",maxof(3, i, j[42], 0));
}

For more information, please see The C Book and stdarg.h.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...