Printf as function argument

Usually using a function:

my_func("test");

Can this parameter be used like this?

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

int my_func (const char *)

+3
source share
5 answers

Yes, you can use the return value printfas a parameter to the function.
But remember that printfsuccess returns the number of characters written.
So

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

passes 6functions foonot bar123.

If you want to pass the string that prints printf, you can use the function sprintf. It is similar to printf, but instead of writing to the console, it is written to the char array.

+8
    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)
+4

; printf() , . s[n]printf() , .

+2

printf .

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

, my_func, my_func . , , .

+1

, , printf accept, - , . 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 */
}

If you want to add additional arguments that are not format related, add them before the 'fmt' argument. Fmt is passed to va_start to say "variable arguments begin after that."

+1
source

Source: https://habr.com/ru/post/1771452/


All Articles