But why is it not installed by default?
Perhaps due to historical reasons due to which compilers are not smart enough. Perhaps because you might have a prototype of the varargs function that doesn't really care about varargs, and setting up varargs is expensive on this particular system. Perhaps because of the more complex operations in which you perform va_copy , or perhaps you need to restart the arguments several times and call va_start several times.
Short version: because the language speaks about it.
Secondly, it is not clear to me why we need to give an account as an argument. Can C ++ automatically determine the number of arguments?
It is not that all this is count . This is the last argument to the function. va_start needs to find out where varargs are. Most likely, this is due to the historical reasons for the old compilers. I do not understand why today it is impossible to implement in a different way.
As the second part of your question: no, the compiler does not know how many arguments were sent to this function. It may not even be in the same compilation unit or even in the same program, and the compiler does not know how the function will be called. Imagine a library with a varargs function, such as printf . When you compile your libc, the compiler does not know when and how programs will call printf . In most ABIs (ABIs are conventions on how functions are called, how arguments are passed, etc.), There is no way to know how many arguments a function call received. It is wasteful to include this information in a function call, and it is almost never needed. So you need to have a way to tell the varargs function how many arguments it received. Access to va_arg beyond the number of arguments that were actually passed is undefined behavior.
Then it is not clear to me why we use va_end (ap). What has he changed?
Most va_end architectures do not matter. But there are some architectures with complex semantics for passing arguments, and va_start can even potentially store malloc memory, then you need va_end to free this memory.
The short version is also here: because the language speaks about it.
Art Apr 03 '13 at 13:03
source share