C Functions with Variable Numbers of Arguments There are functions in C/C++(printf()being one of them) that do not have a fixed list of arguments. Do you know how to defining a functions with Variable Numbers of Arguments? 6
C Functions with Variable Numbers of Arguments • There are functions in C/C++ (printf() being one of them) that do not have a fixed list of arguments. • Do you know how to defining a functions with Variable Numbers of Arguments? 6
Variable_args function Consider an Example format1.c:a function with variable numbers of arguments 1 //Example Ellipsis and va_args 2 #include "stdio.h" 第一个可选参数地址 3 #include "stdarg.h" #define va_start(ap,v)(ap =(va_list)&v +_INTSIZEOF(v)) 4 5 int print_ints(unsigned char count,...) 6 7 va_list arg_list; 8 va_start(arg_list,count); 9 while (count--) 下一个参数地址 #define va_arg(ap,t)(*(t *)((ap +=_INTSIZEOF(t))_INTSIZEOF(t))) printf("%i\n",va_arg(arg_list,int)); 1314 va_end(arg_list); ∥将指针置为无效 16 #define va_end(ap)(ap =(va_list)0) 1 int main(void) 18 19 print_ints(4,1,2,3,4); 20 print_ints(2,100,200); 21
Variable_args function • Consider an Example format1.c: a function with variable numbers of arguments 7 //第一个可选参数地址 #define va_start(ap,v) ( ap = (va_list)&v + _INTSIZEOF(v)) //下一个参数地址 #define va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) _INTSIZEOF(t)) ) // 将指针置为无效 #define va_end(ap) ( ap = (va_list)0)
Variable_args function ·output: oyjb@ubuntu:~/Desktop oyjbdubuntu:~$cd Desktop/ oyjbaubuntu:~/Desktops gcc Test.c oyjbdubuntu:~/Desktops ./a.out 1 2 3 A 100 200 oyjbaubuntu:~/Desktops 8
Variable_args function • output: 8
Variable_args function Let's see what happens if we supply our function with an incorrect number of arguments-for example,passing less values than count. To do this,we change the following lines: 17曰int main(void) 18 { 19 print_ints(6,1,2,3,4); /2 values short * 20 print_ints(5,100,200); /3 values short * 21 oyjb@ubuntu:~/Desktops gcc Test.c oyjbdubuntu:~/Desktops./a.out 2 3 4 -2100901424 4196112 Why 100 200 output this ⊙ data? 4196112 oyjbaubuntu:~/Desktops 9
Variable_args function • Let’s see what happens if we supply our function with an incorrect number of arguments—for example, passing less values than count. To do this, we change the following lines: 9 Why output this data?
Correct Stack Operation with va_args We know how a stack can be used to pass arguments to functions and store local variables. Let's see how stack is operated in case of "correct"and "incorrect"calls to the print_int function. 10
Correct Stack Operation with va_args • We know how a stack can be used to pass arguments to functions and store local variables. • Let’s see how stack is operated in case of “correct” and “incorrect” calls to the print_int function. 10