1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <stdarg.h> // va_list, va_start(…), va_arg(…), va_end(…)
// Must include stdarg.h for variadic function
// VARIADIC FUNCTION to add an arbitary number of numbers.
// - Variadic functions let you accept an arbitary number of parameters.
// - Variadic function must take at least one parameter
// - Arguments may be of different types.
// - You may call va_arg only as many times as there are additional arguments.
// - mintf("…"); // do not call va_arg(…) at all
// - mintf("…", A); // call va_arg(…) exactly one time.
// - mintf("…", A, B); // call va_arg(…) exactly two times.
// - mintf("…", A, B, C); // call va_arg(…) exactly three times.
// - Additional arguments are not an array
// - You cannot access the i'th element arbitrarily.
// - Wouldn't work since the types may vary.
// - Additional arguments must be accessed…
// - in order
// - in a single pass
// - starting from the first additional argument (if any)
// ASSUME the caller follows the rules given in the documentation for the function.
// - For public functions in this class (i.e., given in the requirements), the spec
// is the document.
// - For these examples here, the comment is the document.
int sum(int n_first, ...) { // ... means and 0 or more parameters.
// ↑
// last named parameter is n_first
// sum(…) returns the sum of the arguments.
// - last argument must be 0. That signifies the end.
va_list more_args; // more_args is a name that you can choose.
va_start(more_args, n_first); // va_start(«va_list object», «last named parameter»);
int arg = n_first;
int sum_of_args = arg;
while(arg != 0) {
arg = va_arg(more_args, int);
// va_arg(«va_list object», «expected arg type»).
sum_of_args += arg;
}
va_end(more_args); // clean up (to avoid memory leaks, etc.). (penalty if you forget)
return sum_of_args;
}
int main(int argc, char* argv[]) {
printf("sum(0) == %d\n", sum(0)); //////////////////// Step 1 (TDD)
printf("sum(5, 0) == %d\n", sum(5, 0)); ////////////// Step 2
printf("sum(5, 7, 0) == %d\n", sum(5, 7, 0)); //////// Step 3
printf("sum(3, 5, 7, 0) == %d\n", sum(3, 5, 7, 0)); // Step 4
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2022 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.