简体   繁体   中英

C: how to write a function like printf

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.

1) You've answered the question yourself - printf must parse the format string to decide how many arguments to take in the va_list.

2) When it parses the format list it will track the types of the arguments specified in the format list and call var_arg with the appropriate type.

Also see - the interesting stuff is in vfprintf() , here's the linked source, though there might be a more readable (if less efficient) version .

Edit: There's a portable implementation of snprintf here , that looks more readable (found here Looking for C source code for snprintf() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM