The format Function Attribute

Function attribute format provides a way to identify user-defined functions that take format strings as arguments so that calls to these functions will be type-checked against a format string, similar to the way the compiler checks calls to the functions printf, scanf, strftime, and strfmon for errors. The feature is an orthogonal extension to C89, C99, Standard C++ and C++98, and has been implemented to facilitate porting applications developed with GNU C and C++.

The syntax is shown in the following diagram. The first argument indicates the archetype for how the format string should be interpreted.

                      .-,--------------------------------------------------------------------------.
                      V                                                                            |
>>-__attribute__--((----+-format-----+--(--+-printf-------+--,--string_index--,--first_to_check--)-+--))-><
                        '-__format__-'     +-scanf--------+
                                           +-strftime-----+
                                           +-strfmon------+
                                           +-__printf__---+
                                           +-__scanf__----+
                                           +-__strftime__-+
                                           '-__strfmon__--'
 
 

where

string_index
Is a constant integral expression that specifies which argument in the declaration of the user function is the format string argument. In C++, the minimum value of string_index for nonstatic member functions is 2 because the first argument is an implicit this argument. This behavior is consistent with that of GNU C++.

first_to_check
Is a constant integral expression that specifies the first argument to check against the format string. If there are no arguments to check against the format string (that is, diagnostics should only be performed on the format string syntax and semantics), first_to_check should have a value of 0. For strftime-style formats, first_to_check is required to be 0.

It is possible to specify multiple format attributes on the same function, in which case, all apply.

void my_fn(const char* a, const char* b, ...) 
       __attribute__((__format__(__printf__,1,0), __format__(__scanf__,2,3)));

It is also possible to diagnose the same string for different format styles. All styles are diagnosed.

void my_fn(const char* a, const char* b, ...) 
       __attribute__((__format__(__printf__,2,3),
                      __format__(__strftime__,2,0),
                      __format__(__scanf__,2,3)));

Related References

IBM Copyright 2003