But why it is not set to the beginning by default?
Maybe because of historical reasons from when compilers weren't smart enough. Maybe because you might have a varargs function prototype which doesn't actually care about the varargs and setting up varargs happens to be expensive on that particular system. Maybe because of more complex operations where you do va_copy
or maybe you want to restart working with the arguments multiple times and call va_start
multiple times.
The short version is: because the language standard says so.
Second, it is not clear to me why we need to give count as an argument. Can't C++ automatically determine the number of the arguments?
That's not what all that count
is. It is the last named argument to the function. va_start
needs it to figure out where the varargs are. Most likely this is for historical reasons on old compilers. I can't see why it couldn't be implemented differently today.
As the second part of your question: no, the compiler doesn't know how many arguments were sent to the function. It might not even be in the same compilation unit or even the same program and the compiler doesn't know how the function will be called. Imagine a library with a varargs function like printf
. When you compile your libc the compiler doesn't know when and how programs will call printf
. On most ABIs (ABI is the conventions for how functions are called, how arguments are passed, etc) there is no way to find out how many arguments a function call got. It's wasteful to include that information in a function call and it's almost never needed. So you need to have a way to tell the varargs function how many arguments it got. Accessing va_arg
beyond the number of arguments that were actually passed is undefined behavior.
Then it is not clear to me why do we use va_end(ap). What does it change?
On most architectures va_end
doesn't do anything relevant. But there are some architectures with complex argument passing semantics and va_start
could even potentially malloc memory then you'd need va_end
to free that memory.
The short version here is also: because the language standard says so.