C语言可变长参数函数与默认参数提升(3)

然后,调用者将提升后的参数传递给被调用者。
所以,my_printf是绝对无法接收到上述类型的实际参数的。

上面的代码的42与43行,应该改为:
int c = va_arg(ap,int);
printf("%c",c);

同理, 如果需要使用short和float, 也应该这样:
short s = (short)va_arg(ap,int);
float f = (float)va_arg(ap,double);

再来看一个具体的例子吧:

#include <stdarg.h>
#include <stdio.h>
 
void read_args_from_va_good(int i, ...)
{
    va_list arg_ptr;
    va_start(arg_ptr, i);
 
    /* This is right. */
    printf("%c\n", va_arg(arg_ptr, int));
    printf("%d\n", va_arg(arg_ptr, int));
    printf("%f\n", va_arg(arg_ptr, double));
 
    va_end(arg_ptr);
}
 
void read_args_from_va_bad(int i, ...)
{
    va_list arg_ptr;
    va_start(arg_ptr, i);
 
    /* This is wrong. */
    printf("%c\n", va_arg(arg_ptr, char));
    printf("%d\n", va_arg(arg_ptr, short));
    printf("%f\n", va_arg(arg_ptr, float));
 
    va_end(arg_ptr);
}
 
int main()
{
    char c = 'c';
    short s = 0;
    float f = 1.1f;
 
    read_args_from_va_good(0, c, s, f);
    read_args_from_va_bad(0, c, s, f);
 
    return 0;
}

上面的代码用gcc4.4.0编译,会有警告:

va_arg.c: In function ‘read_args_from_va_bad’:
va_arg.c:47: warning: ‘char’ is promoted to ‘int’ when passed through ‘...’
va_arg.c:47: note: (so you should pass ‘int’ not ‘char’ to ‘va_arg’)
va_arg.c:47: note: if this code is reached, the program will abort
va_arg.c:48: warning: ‘short int’ is promoted to ‘int’ when passed through ‘...’
va_arg.c:48: note: if this code is reached, the program will abort
va_arg.c:49: warning: ‘float’ is promoted to ‘double’ when passed through ‘...’
va_arg.c:49: note: if this code is reached, the program will abort

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/b60962e878050aa4d5178d1f8d78b66c.html