Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get printf style compile-time warnings or errors

I would like to write a routine like printf, not functionally-wise, but rather I'd like the routine to have the same time compile check characteristics as printf.

For example if i have:

{
   int i;
   std::string s;
   printf("%d %d",i);
   printf("%d",s.c_str());
}

The compiler complains like so:

1 cc1plus: warnings being treated as errors
2 In function 'int main()':
3 Line 8: warning: too few arguments for format
4 Line 9: warning: format '%d' expects type 'int', but argument 2 has type 'const char*'

code example

Are printf and co special functions that the compiler treats differently or is there some trick to getting this to work on any user defined function? The specific compilers I'm interested in are gcc and msvc

like image 690
Hippicoder Avatar asked Jun 23 '10 20:06

Hippicoder


People also ask

Is printf a compile time?

Actually printf doesn't have any inherent compile-time safety at all. It just happens that some more recent compilers have implemented special checks given that they know exactly what a format string means in terms of the additional parameters.

How do I get a printf number?

printf("Enter an integer: "); scanf("%d", &number); Finally, the value stored in number is displayed on the screen using printf() . printf("You entered: %d", number);

Which of the following is format specification for printing string in printf ()?

Option a is the correct answer. %s is used as the format specifier which prints a string in C printf or scanf function. In C, %s allows us to print by commanding printf() to print any corresponding argument in the form of a string. The argument used is "char*" for %s to print.


1 Answers

Different compilers might implement this functionality differently. In GCC it is implemented through __attribute__ specifier with format attribute (read about it here). The reason why the compiler performs the checking is just that in the standard header files supplied with GCC the printf function is declared with __attribute__((format(printf, 1, 2)))

In exactly the same way you can use format attribute to extend the same format-checking functionality to your own variadic functions that use the same format specifiers as printf.

This all will only work if the parameter passing convention and the format specifiers you use are the same as the ones used by the standard printf and scanf functions. The checks are hardcoded into the compiler. If you are using a different convention for variadic argument passing, the compiler will not help you to check it.

like image 77
AnT Avatar answered Oct 13 '22 14:10

AnT