printf 如何处理它的参数? [英] How does printf handle its arguments?

查看:28
本文介绍了printf 如何处理它的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

printf 如何处理它的参数?我知道在 C# 中我可以使用 params 关键字来做类似的事情,但我无法在 C 中完成?

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 ?

推荐答案

这样的函数被称为可变参数函数.您可以使用 ... 在 C 中声明一个,如下所示:

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

int f(int, ... );

然后您可以使用 va_startva_argva_end 来处理参数列表.下面是一个例子:

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\n",maxof(3, i, j[42], 0));
}

有关更多信息,请参阅The C Bookstdarg.h.

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

这篇关于printf 如何处理它的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆