Translate

Thursday, June 13, 2013

Variadic Functions

Hi there again!
This time I'm gonna show you a very simple program to demonstrate how you can use variadic functions.
They are functions that accept a variable number of arguments and are very useful for many mathematical and logical operations programming.

 1 /* 
 2  *    Even being very basic, this program shows how to use variadic functions
 3  *
 4  *    Gabriel Marques 
 5  *    snortt@gmail.com
 6  *
 7  */
 8 
 9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 
13 /* This one is needed by variadic functions */
14 #include <stdarg.h>
15 
16 /* 
17  * Prototypes
18  * 
19  * As you can see, variadic functions are declared with a coma and the ellipsis (", ...")
20  */
21 void print_message(const char *, ...);
22 int sum_of(int, ...);
23 
24 int main(int argc, char *argv[]) {
25 
26     print_message("This is a test %s %c", "...", '\n');
27     printf("Sum of 1 2 3 = %d\n", sum_of(3,1,2,3));
28     
29     exit (EXIT_SUCCESS);
30 }
31 
32 void print_message(const char *str, ...) {
33     /* This creates the pointer to the args list*/
34     va_list args;
35     
36     /* This initializes the args list. Points to first element AFTER str */
37     va_start(args, str);
38 
39     /* Now we print all he args by making use of the proper function */
40     vprintf(str, args);
41 
42     /* Now we clean up the mess we made inside the program stack */
43     va_end(args);
44 }
45 
46 /* This function receives the count of values to be added and the values themselves */
47 int sum_of(int count, ...) {
48     
49     int i, sum = 0;
50     /* This creates the pointer to the args list*/
51     va_list args;
52 
53     /* This initializes the args list. Points to first element AFTER count */
54     va_start(args, count);
55 
56    for (i = 0; i < count; i++) {
57         /* Steps through the args list and adds each value it finds until it reaches the limit (count) */
58         sum += va_arg(args, int);
59     }
60     
61     /* Now we clean up the mess we made inside the program stack */
62     va_end(args);
63 
64     return sum;
65 }

I hope this quick text could help you!


No comments:

Post a Comment