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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <stdarg.h>
// Okay to copy/adapt this example
void print_integers(int num_of_ints, char* prefix, ...) {
// declare the list of extra arguments
va_list more_args;
// populate the list starting after prefix
va_start(more_args, prefix);
// need a parameter telling us how many arguments to pull
// in this function caller provides a number
for (int i = 0; i < num_of_ints; i++) {
// grab a single integer argument
int extra_int = va_arg(more_args, int);
printf("%s%d\n", prefix, extra_int);
}
// clean up arguments afterwards
va_end(more_args);
}
void print_strings(int num_of_strings, ...) {
// declare the list of extra arguments
va_list extra_args;
// populate the list starting after num_of_strings
va_start(extra_args, num_of_strings);
// need a parameter telling us how many arguments to pull
// in this function caller provides a number
for (int i = 0; i < num_of_strings; i++) {
// grab a single string argument
char* extra_str = va_arg(extra_args, char*);
printf("%s\n", extra_str);
}
// clean up arguments afterwards
va_end(extra_args);
}
int main(int argc, char* argv[]) {
print_integers(5, "* ", 1, 1, 2, 3, 5, 8);
print_strings(3, "Hello", "ECE", "264");
return EXIT_SUCCESS;
}
/* 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.