Search code examples
cformat-specifiers

Does sprintf() require format specifiers to work properly?


I have read the post sprintf format specifier replace by nothing, and others related, but have not seen this addressed specifically.

Until today, I have never seen sprintf used with only 2 arguments.
The prototype my system uses for sprintf() is:

int sprintf (char Target_String[], const char Format_String[], ...);

While working with some legacy code I ran across this: (simplified for illustration)

char toStr[30];
char fromStr[]={"this is the in string"};
sprintf(toStr, fromStr);

My interpretation of the prototype is that the second argument should be comprised of a const char[], and accepting standard ansi C format specifiers such as these.

But the above example seems to work just fine with the string fromStr as the 2nd argument.
Is it purely by undefined behavior that this works?, or is this usage perfectly legal?

I a working on Windows 7, using a C99 compiler.


Solution

  • The behavior you are observing is correct, a format string is not required to have any conversion specifiers. In this case the variable-length argument list, represented by ..., has length of zero. This is perfectly legal, although it's definitely less efficient than its equivalent

    strcpy(toStr, fromStr);