Home > Software engineering >  How can the compiler able to warn if I pass more arguments to printf function?
How can the compiler able to warn if I pass more arguments to printf function?

Time:08-10

In general, when using Variadic functions, we always give some sort for number of expected inputs, but never know how many are passed.

Then, how does compiler able to detect when I passed more arguments than required to printf() function ?.

Below is the sample code

#include <stdio.h>

int main()
{
    
    printf("Hello World", 2); 
 
    return 0;
}

Output:

main.c: In function ‘main’:
main.c:6:12: warning: too many arguments for format [-Wformat-extra-args]
    6 |     printf("Hello World", 2,3,4);
      |            ^~~~~~~~~~~~~
Hello World

I was using the following online compiler : https://www.onlinegdb.com/online_c_compiler

CodePudding user response:

The used compiler is smart enough(*) to recognize printf() as a special function, in this case a function of the standard library. This function receives a format string. If the compiler can read this format string, it interprets the format codes like printf() will do. And so it expects the number and types of the following arguments.

You can use this feature for your own printf-like function, for example (shamelessly copied from GCC's manual):

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

(*) "Smart enough" means that printf() is declared in "stdio.h" with this attribute, and the compiler knows how to process this attribute.

  • Related