不使用 stdarg.h 的可变长度参数 [英] Variable Length Arguments without using stdarg.h
问题描述
我试图通过检查堆栈来理解和实现一种处理可变长度参数函数的方法,但我不知道从哪里开始以及如何开始.我发现以下链接很有帮助,但我仍然不太明白我如何能够在 c 中为类似打印功能的东西做这样的事情.
I'm trying to understand and implement a way to handle variable length argument function by checking the stack, but I have not idea on where and how to start. I have found the following links helpful but I still don't quite understand how I would be able to something like this in c for something like a print function.
http://www.swig.org/Doc1.3/Varargs.html
推荐答案
查看 C Reference Manual by Dennis M. Ritchie
在 printf()
的实现中早在 ...
code> 和
:
Look in the C Reference Manual by Dennis M. Ritchie
at the implementation of printf()
that existed long before ...
and <stdarg.h>
:
printf ( fmt, args )
char fmt [ ] ;
{
...
int *ap, x, c ;
ap = &args ; /* argument pointer */
...
for ( ; ; ) {
while ( ( c = *fmt++ ) != ´%´ ) {
...
switch ( c = *fmt++) {
/* decimal */
case ´d ´:
x = *ap++ ;
if(x < 0) {
x = -x;
if ( x<0 ) { /* is - infinity */
printf ( "-32768" ) ;
continue ;
}
putchar ( ´-´);
}
printd(x);
continue ;
...
}
...
}
...
}
}
printd(n)
{
int a ;
if ( a=n/10 )
printd(a);
putchar ( n%10 + ´0´ ) ;
}
您可以忽略函数和参数声明的旧(AKA K&R)语法:
You can disregard the old (AKA K&R) syntax of function and parameter declaration:
printf ( fmt, args )
char fmt [ ] ;
甚至用更现代的替换它:
and even replace it with a more modern:
int printf ( char fmt[], int args )
但思路是一样的,你直接得到一个指向第一个可选参数(args
)的指针,就像上面代码中用ap = &args;
,然后不断增加它以访问更多参数.
but the idea is the same, you get a pointer to the first optional argument (args
) directly, as is done in the above code with ap = &args;
, and then keep incrementing it to get access to further arguments.
或者你可以间接地做,使用最后一个非可选参数作为起点:
Or you can do it indirectly, using the last non-optional argument as the starting point:
int printf ( char fmt[], ... )
{
...
int *ap, x, c ;
ap = &fmt ; /* argument pointer */
ap++; /* ap now points to first optional argument */
...
}
这说明了机制.
请注意,如果您这样编写代码,它将无法移植,甚至可能无法与您的编译器一起使用.
Beware, if you write your code like this, it won't be portable and it may even fail work with your compiler.
这篇关于不使用 stdarg.h 的可变长度参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!