Search code examples
cc-stringsstring-literals

How to print to the return value of a function, using format modifiers, in C?


Don't know if this is possible. I've been searching for it but nothing comes up.

I'd like to have a function that merges multiple values and returns them as a string literal (so no malloc and subsequent free). This could be achieved by printing to the return value (if that makes sense and is possible), or maybe using fprintf with a literal as destination, instead of say stdout, and then that literal could be returned.

The parameters of the function below are just an example, there could be other types such as long, etc.

#include <stdio.h>

char *format_and_return_literal(const char *s, int n, char c)
{
        int m = 7;

        //(1):  Possible to fprintf to return value of function?
        //fprintf(<func-return-literal>, "hello %s: %d %d %c", s, m, n, c);
        //return <func-return-literal>;

        // or

        //(2):  Possible to return string literal made of above parameters?
        //return "hello %s: %d %d %c", s, m, n, c)
}

int main()
{
        printf("%s\n", format_and_return_literal("foo", 33, 'M'));
        return 0;
}

Update: Thank you all. Perhaps the terminology I used wasn't the most correct, but I achieved what I wanted following @Davislor's suggestion of using a static buffer. I'm aware of snprintf but thank you anyway, @PeterJ.

char *format_and_return_literal(const char *s, int n, char c)
{
        static char buf[1024];
        int m = 7;

        snprintf(buf, sizeof(buf), "hello %s: %d %d %c", s, m, n, c);

        return buf;
}

Solution

  • You can snprintf to a fixed-size, static buffer and return that. Subsequent calls would then overwrite the previous return value. Alternatively, pass in the destination buffer, owned by the caller. as an argument.