title: An example of use of varargs in C
body: <p><a href="http://en.wikipedia.org/wiki/Varargs#C.2C_Objective-C.2C_C.2B.2B.2C_and_D" rel="noreferrer">Here</a> I found an example of how varargs can be used in C.</p>
  
  <pre><code>#include &lt;stdarg.h&gt;
  
  double average(int count, ...)
  {
      va_list ap;
      int j;
      double tot = 0;
      va_start(ap, count); //Requires the last fixed parameter (to get the address)
      for(j=0; j&lt;count; j++)
          tot+=va_arg(ap, double); //Requires the type to cast to. Increments ap to the next argument.
      va_end(ap);
      return tot/count;
  }
  </code></pre>
  
  <p>I can understand this example only to some extent. </p>
  
  <ol>
  <li><p>It is not clear to me why we use <code>va_start(ap, count);</code>. As far as I understand, in this way we set the iterator to its first element. But why it is not set to the beginning by default? </p></li>
  <li><p>It is not clear to me why we need to give <code>count</code> as an argument. Can't C automatically determine the number of the arguments? </p></li>
  <li><p>It is not clear to me why we use <code>va_end(ap)</code>. What does it change? Does it set the iterator to the end of the list? But is it not set to the end of the list by the loop? Moreover, why do we need it? We do not use <code>ap</code> anymore; why do we want to change it?</p></li>
  </ol>