There are many functions in the C-language library that are similar to PRINTF,SCANF, and the number of arguments received by these functions is indeterminate. These functions are actually implemented through the Va_list,va_start,va_arg,va_end macro definition in the <stdarg.h> file. In addition, when we know the memory structure of the program runtime, we can also get the actual parameter values by directly accessing these memory spaces (in fact, the relevant macro definitions in the Stdarg.h file are doing so).
#include <stdio.h> #include <stdlib.h> #include <stdarg.h>int sum1 (int nums); int sum2 (int nums); int Main () {int result1 = 0;int Result2 = 0;RESULT1 = Sum1 (5, 1, 2, 3, 4, 5); result2 = sum2 (5, 1, 2, 3, 4, 5);p rintf ("Result1 I S%d\n ", RESULT1);p rintf (" Result2 is%d\n ", result2); System (" pause "); Stack is from high address to low address growth, C language function parameter is from right to left into the stack//c language in the stack is determined by the function caller (_ccall)//c++ in the stack is the function itself (_stdcall), C + + also support variable parameters,// But needs to be declared as int sum1 (int nums,...) form int sum1 (int nums) {int result = 0;int *argptr = &nums;//Get the address of the parameter nums for (int i = 0; i < nums; i++) Result + = * (++ar GPTR); return result;} Use the VA_LIST,VA_START,VA_END,VA_ARG macro definition in <stdarg.h> to implement int sum2 (int nums) {int result = 0;va_list Argptr;va_start ( Argptr,nums); for (int i = 0; i < nums; i++) result + = Va_arg (argptr, int); Va_end (argptr); return result;}
The program runs the following results
How to implement variable parameters in C language