As you can see from the code snippet below, I have declared one char
variable and one int
variable. When the code gets compiled, it must identify the data types of variables str
and i
.
Why do I need to tell again during scanning my variable that it's a string or integer variable by specifying %s
or %d
to scanf
? Isn't the compiler mature enough to identify that when I declared my variables?
#include <stdio.h>
int main ()
{
char str [80];
int i;
printf ("Enter your family name: ");
scanf ("%s",str);
printf ("Enter your age: ");
scanf ("%d",&i);
return 0;
}
Because there's no portable way for a variable argument functions like scanf
and printf
to know the types of the variable arguments, not even how many arguments are passed.
See C FAQ: How can I discover how many arguments a function was actually called with?
This is the reason there must be at least one fixed argument to determine the number, and maybe the types, of the variable arguments. And this argument (the standard calls it parmN
, see C11(ISO/IEC 9899:201x) §7.16 Variable arguments ) plays this special role, and will be passed to the macro va_start
. In another word, you can't have a function with a prototype like this in standard C:
void foo(...);