Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Variadic functions provide the ability to specify can accept a variable number of arguments to a function, but they can be are problematic. Variadic functions contain define an implicit contract between the function writer and the function user that must be made to establish how many arguments are passed on an invocation. If care is not exercised allows the function to determine the number of arguments passed passed in any particular invocation. Failure to exercise care when invoking a variadic function to ensure that it knows when to stop processing arguments and that , or incorrect management of the argument list is used incorrectly, there may be dangerous consequences. It should be noted that variadic functions must always have an ellipsis as a parameter, or the result is undefinedresult in stack corruption.

Argument Processing

Wiki Markup
In the following code example,
a
 the variadic function
called
 {{average()
(taken from an article written by Robert Seacord for Linux World Magazine on variadic functions) is used to determine the average value of its passed integer arguments. The function will stop processing arguments when it sees that the argument is -1
}} is used to determine the average value of its passed integer arguments \[[Seacord 05c|AA. C References#Seacord 05c]\]. The function stops processing arguments when it sees that the argument is {{\-1}}.

Code Block
int average(int first, ...) {
  size_t count = 0;
  int sum = 0;
  int i = first;
  va_list marker;

  va_start(marker, first);

  while (i != -1) {
    sum += i;
    count++;
    i = va_arg(marker, int);
  }

  va_end(marker);
  return(count ? (sum / count) : 0);
}

...

Wiki Markup
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.15, "Variable arguments"; 7.19.6.8 "The {{vfprintf}} function"
\[[Seacord 05c|AA. C References#Seacord 05c]\]