简体   繁体   English

C:如何编写像printf这样的函数

[英]C: how to write a function like printf

I have learnt to use library stdarg.h to have function with unknown number of arguments. 我学会了使用库stdarg.h来使用具有未知数量参数的函数。 Here is a simple function how to use this : 这是一个简单的函数如何使用:

void print(int args,...){
    va_list ap;
    va_start(ap, args);
    int i = 0;
    for(i=0; i<args; i++){
        printf("%d\n",va_arg(ap, int));
    }
    va_end(ap);
}

Base on above code, there are two main constrains that I don't know how printf can overcome: 基于上面的代码,有两个主要的约束,我不知道printf如何克服:

1) fixed number arguments : mean, in almost vardiac function, you need to include number of args. 1)固定数量参数 :意思是,在几乎vardiac函数中,你需要包含args的数量。 But when I write printf , I don't have to include this number. 但是当我写printf ,我不必包含这个数字。 I have thought that before printf really using arguments, it has counted number of argument before (by counting number % in the first string). 我认为在printf真正使用参数之前,它已经计算了之前的参数数量(通过计算第一个字符串中的数字%)。 But again, I think this solution is a little bit not efficient. 但同样,我认为这个解决方案有点效率不高。 It must go through three pharses : counting number of arguments, and put this arguments into stack, and lastly put all into the screen. 它必须通过三个pharses:计算参数数量,并将这些参数放入堆栈,最后将所有参数放入屏幕。

2) All arguments must have same type: As you see at the line : printf("%d\\n",va_arg(ap, int)); 2)所有参数必须具有相同的类型:如下所示printf("%d\\n",va_arg(ap, int)); . So, every argument in the list must have the same type. 因此,列表中的每个参数都必须具有相同的类型。 And as we know, this is not the must in printf. 而且正如我们所知,这不是printf中必须的。 You can print double together with integer or the string. 您可以使用整数或字符串打印double。 If we treat all of this just like a string, so this line should be error because wrong syntax : 如果我们将所有这些视为一个字符串,那么这一行应该是错误的,因为错误的语法:

printf("%d",4); //4 cannot treat by string
printf("%d",'4'); // :)) I think this line is better

Please help me explain above two problems. 请帮我解释一下上面两个问题。

1) You've answered the question yourself - printf must parse the format string to decide how many arguments to take in the va_list. 1)你自己回答了这个问题 - printf必须解析格式字符串以决定在va_list中要采用多少个参数。

2) When it parses the format list it will track the types of the arguments specified in the format list and call var_arg with the appropriate type. 2)当它解析格式列表时,它将跟踪格式列表中指定的参数类型,并使用适当的类型调用var_arg

Also see - the interesting stuff is in vfprintf() , here's the linked source, though there might be a more readable (if less efficient) version . 请参阅 - 有趣的东西是在vfprintf() ,这里是链接源,尽管可能有更易读(如果效率更低)的版本

Edit: There's a portable implementation of snprintf here , that looks more readable (found here Looking for C source code for snprintf() ) 编辑:有便携式实施方案的snprintf的位置 ,看起来更具有可读性(这里找到正在寻找的snprintf C源代码() )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM