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
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>                             // - This is required in any program that uses
                                                //   variadic functions (additional arguments).

//                          num_of_nums is the last named parameter to this function.
//                          ┌───┴─────┐
void print_many_numbers(int num_of_nums, ...) { // - The ... stands for the rest of the arguments.
    va_list more_args;                          // - Get a handle to the additional arguments.
    va_start(more_args, num_of_nums);           // - This is required to access them.  Yes, it
                                                //   is weird.
    for(int i = 0; i < num_of_nums; i++) {      //
        int next_num = va_arg(more_args, int);  // - Get the next additional argument.
        printf("%d\n", next_num);               // - Print it.
    }                                           //
                                                //
    va_end(more_args);                          // - This is required after you're done.
}                                               //   Yes, this is weird (too).

// va_arg(…) eats one additional arguments.
// You can only go through the arguments from the start, one by one.
// You cannot skip around.
// You cannot* go through the arguments more than once.
//  (* without some additional tricks that we won't worry about right now)

int main(int argc, char* argv[]) {
    print_many_numbers(4, 768336, 768337, 768338, 768339);
    fputc('\n', stdout)
    print_many_numbers(3, 198372, 198373, 198374);

    return EXIT_SUCCESS;
}

© Copyright 2022 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.