Say, if I do the following:
const char *strFmt = "Value=%d, str=%s, v=%I64d. Is 100%% true";
printf(strFmt, 1, "name", -1);
Is there a function that simply returns how many parameters are needed for strFmt
without filling them in?
Say, if I do the following:
const char *strFmt = "Value=%d, str=%s, v=%I64d. Is 100%% true";
printf(strFmt, 1, "name", -1);
Is there a function that simply returns how many parameters are needed for strFmt
without filling them in?
The usual reason for wanting the number of required parameters is to check one's code. C runtime libraries do this as a side-effect of the printf
function. Source for those (as well as for similar printf-like functions such as StrAllocVsprintf
in Lynx) can be found easily enough.
Because printf
is a varargs function, there is no predefined prototype which tells the "right" number of parameters.
If there are too few parameters, bad things can happen ("undefined behavior"), while extra ones may be ignored. Most modern compilers provide some help, in the form of compile-time warnings.
There is no standard function to count the number of required parameters. The question has been asked before, e.g.,
For whatever historical reason, the function also has (apparently) not been provided by any compiler suite. In most cases, this is because printf
formats are usually checked by the compiler (or static analysis tools such as lint
). Not all compilers do these checks. A few can be told using that some functions aside from printf
and its standard relatives are "printf-like". Visual Studio lacks that feature, but can do some printf-checking (not a lot according to Is there any way to make visual C++ (9.0) generate warnings about printf format strings not matching type of printf's args?).
A string constant is not going to be associated by the compiler with the printf
function. You could make it a #define
and reuse the value in an actual printf
function to get whatever checking the compiler can do.
For instance
#define strFmt "Value=%d, str=%s, v=%I64d. Is 100%% true"
printf(strFmt, 1, "name", -1);
The problem itself is portable: if your program also is portable, you can check it with other tools than the Visual Studio compiler.