繁体   English   中英

printf作为函数的参数

[英]printf as argument of function

通常使用功能:

my_func("test");

我是否可以使用这个参数呢?

my_func(printf("current_count_%d",ad_id));

int my_func(const char * key)

是的,您可以使用printf的返回值作为函数参数。
但请记住, printf on success会返回写入的字符数。
所以

foo(printf("bar%d",123)); 

6传递给foo函数而不是bar123

如果要传递printf打印的字符串,可以使用sprintf函数。 它类似于printf但它不是写入控制台而是写入char数组。

    char buf[64]; /* malloc or whatever */
    int pos = snprintf(buf, sizeof(buf), "current_count_%d", ad_id);
    if (sizeof(buf) <= pos)
                    buf[sizeof(buf)-1] = '\0';
    my_func(buf)

没有; printf()返回打印到stdout的字符数。 使用s[n]printf()创建字符串,然后传递它。

函数printf 返回一个整数

int printf ( const char * format, ... );

因此,只要my_func将整数作为参数,就可以在my_func使用它。 似乎并非如此。

如果您希望将一些可变数量的参数(如printf接受)传递给某个函数,那么您需要查看。 要重现printf(为了参数):

void varargfunc(char *fmt, ...)
{
    char formattedString[2048]; /* fixed length, for a simple example - and
                                   snprintf will keep us safe anyway */
    va_list arguments;

    va_start(arguments, fmt); /* use the parameter before the ellipsis as
                                 a seed */

    /* assuming the first argument after fmt is known to be an integer,
       you could... */
    /*
        int firstArgument = va_arg(arguments, int);
        fprintf(stderr, "first argument was %d", firstArgument);
    */

    /* do an vsnprintf to get the formatted string with the variable
       argument list. The v[printf/sprintf/snprintf/etc] functions
       differ from [printf/sprintf/snprintf/etc] by taking a va_list
       rather than ... - a va_list can't turn back into a ... because
       it doesn't inherently know how many additional arguments it
       represents (amongst other reasons) */
    vsnprintf(formattedString, 2048, fmt, arguments);

    /* formattedString now contains the first 2048 characters of the
       output string, with correct field formatting and a terminating
       NULL, even if the real string would be more than 2047 characters
       long. So put that on stdout. puts adds an additional terminating
       newline character, so this varies a little from printf in that 
       regard. */
    puts(formattedString);

    va_end(arguments); /* clean up */
}

如果要添加与格式无关的其他参数,请在“fmt”参数之前添加它们。 Fmt传递给va_start,表示“变量参数在此之后开始”。

暂无
暂无

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

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