Note: (This may pertain to GCC only)    

 For those of you using printf_to_char().  How many times have you supplied
invalid arguments, or too many/too few and been annoyed at the lack of
compiler warning?

Well, using variable length arguments can cause you headaches because the
compiler doesn't know how many arguments to expect.  GCC is printf() aware,
so it is feasable to check the printf() (and family) for proper arguments
and number thereof.

However, when you roll your own printf() type function, you can run into the
problem I mentioned earlier.
I recently ran into a method to have GCC analyze your function with it's
printf() awareness.

void printf_to_char (CHAR_DATA *, const char *, ...)
      __attribute__ ((format (printf, 2, 3)));

Here's the snip from the manual:

format (archetype, string-index, first-to-check)
The format attribute specifies that a function takes printf, scanf, strftime
or
strfmon style arguments which should be type-checked against a format
string.
For example, the declaration:

extern int
my_printf (void *my_object, const char *my_format, ...)
      __attribute__ ((format (printf, 2, 3)));

causes the compiler to check the arguments in calls to my_printf for
consistency with the printf style format string argument my_format.

The parameter archetype determines how the format string is interpreted, and
should be printf, scanf, strftime or strfmon. (You can also use __printf__,
__scanf__, __strftime__ or __strfmon__.) The parameter string-index
specifies
which argument is the format string argument (starting from 1), while
first-to-check is the number of the first argument to check against the
format
string. For functions where the arguments are not available to be checked
(such
as vprintf), specify the third parameter as zero. In this case the compiler
only checks the format string for consistency. For strftime formats, the
third
parameter is required to be zero.

In the example above, the format string (my_format) is the second argument
of
the function my_print, and the arguments to check start with the third
argument, so the correct parameters for the format attribute are 2 and 3.

The format attribute allows you to identify your own functions which take
format strings as arguments, so that GCC can check the calls to these
functions
for errors. The compiler always (unless -ffreestanding is used) checks
formats
for the standard library functions printf, fprintf, sprintf, scanf, fscanf,
sscanf, strftime, vprintf, vfprintf and vsprintf whenever such warnings are
requested (using -Wformat), so there is no need to modify the header file
stdio.h. In C99 mode, the functions snprintf, vsnprintf, vscanf, vfscanf and
vsscanf are also checked. Except in strictly conforming C standard modes,
the
X/Open function strfmon is also checked as are printf_unlocked and
fprintf_unlocked.

Reply via email to