Use of variable parameters in C Language
Mainly involved Functions
Va_list ap declares a pointer
Va_start (ap, arg) points the ap to the final parameter arg.
Va_arg (ap, size) adds the address stored by the ap to size, pointing to the next Parameter
Va_end (ap) assigns an ap value to NULL.
# Include
# Include
Int sum (int ,...); int main (void) {printf (Sum of 10, 20 and 30 = % d, sum (3, 10, 20, 30); printf (Sum of 4, 20, 25 and 30 = % d, sum (4, 4, 20, 25, 30); return 0;} int sum (int num_args ,...) {int val = 0; va_list ap; // pointer to the parameter int I; va_start (ap, num_args ); // point the pointer ap to the final parameter for (I = 0; I <num_args; I ++) {val + = va_arg (ap, int ); // va_arg (), point the pointer ap to the first address of the Variable Parameter} va_end (ap); // assign the pointer ap to NULL return val ;}
Running result:
Sum of 10, 20, and 30 = 60
Sum of 4, 20, 25, and 30 = 79