Versions Compared

Key

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

...

Wiki Markup
In the following code example, the variadic function {{average()}} is used to determine the average value of its passed positive integer arguments \[[Seacord 05c|AA. C References#Seacord 05c]\].  The function processes arguments until it finds one with a value of {{\-1}}, AKA {{va_eol}}.

Code Block
enum {va_eol = -1};

unsigned int average(int first, ...) {
  size_t count = 0;
  unsigned int sum = 0;
  int i = first;
  va_list markerargs;

  va_start(markerargs, first);

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

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

...

Code Block
bgColor#ffcccc
int avg = average(1, 4, 6, 4, 1);

The omission of the -1 va_eol terminating value means that the function will continue to process values from the stack until it encounters a -1 va_eol by coincidence or an error occurs.

...

The following call maintains the contract by adding a -1 va_eol as the last argument.

Code Block
bgColor#ccccff
int avg = average(1, 4, 6, 4, 1, -1va_eol);

Non-Compliant Code Example

...