I have learnt to use library stdarg.h
to have function with unknown number of arguments. Here is a simple function how to use this :
void print(int args,...){
va_list ap;
va_start(ap, args);
int i = 0;
for(i=0; i<args; i++){
printf("%d\n",va_arg(ap, int));
}
va_end(ap);
}
Base on above code, there are two main constrains that I don't know how printf
can overcome:
1) fixed number arguments : mean, in almost vardiac function, you need to include number of args. But when I write printf
, I don't have to include this number. I have thought that before printf
really using arguments, it has counted number of argument before (by counting number % in the first string). But again, I think this solution is a little bit not efficient. It must go through three pharses : counting number of arguments, and put this arguments into stack, and lastly put all into the screen.
2) All arguments must have same type: As you see at the line : printf("%d\n",va_arg(ap, int));
. So, every argument in the list must have the same type. And as we know, this is not the must in printf. You can print double together with integer or the string. If we treat all of this just like a string, so this line should be error because wrong syntax :
printf("%d",4); //4 cannot treat by string
printf("%d",'4'); // :)) I think this line is better
Please help me explain above two problems.