FunctionCodeIt is generated during compilation. For a function with an indefinite number of parameters (or even the same type for each parameter), how does the compiler support such a function.
1 # Include < Stdio. h >
2 # Include < String . H >
3 # Include < Stdarg. h >
4
6 Int T (...)
7 {
8 Return 0 ;
9 }
10 /* The function prototype Declaration requires at least one definite parameter. Note the ellipsis in brackets. */
11 Int Demo ( Char * ,...);
12
13
14 Void Main ( Void )
15
16 {
17 Demo ( " Demo " , " This " , " Is " , " A " , " Demo! " , " \ 0 " );
18 }
19
20 Int Demo ( Char * MSG ,...)
21 {
22 Va_list argp; /* Define the structure for saving function parameters */
23 Int Argno = 0 ; /* Record parameter count */
24 Char * Para; /* Store extracted string Parameters */
25
26 Va_start (argp, MSG );
27 While ( 1 )
28 {
29 Para = Va_arg (argp, Char * );
30 If (Strcmp (para, " \ 0 " ) = 0 ) /* Use an empty string to indicate that the parameter is input. */
31 Break ;
32
33 Printf ( " Parameter # % d: % s \ n " , Argno, para );
34 Argno ++ ;
35 }
36 Va_end (argp ); /* Set argp to null */
37
38 Return 0 ;
39 }
Interesting is to introduce several macros.
First look at this:
# DEFINE _ intsizeof (N) (sizeof (n) + sizeof (INT)-1 )&~ (Sizeof (INT)-1 ))
For memory alignment, the length of N can be converted to a multiple of sizeof (INT. For example, sizeof (n) = 9, sizeof (INT) = 4,
SO _ intsizeof (n) = (9 + 4-1 )&~ (4-1) = 12/3 = 4. That is, to convert 9 to 12, add a 3 for the border peer.
Here is the proof of closing this:
Pretty classic: http://blogold.chinaunix.net/u/1129/showart_397677.html
// # Define va_start _ crt_va_start
// # DEFINE _ crt_va_start (AP, V) (AP = (va_list) _ addressof (v) + _ intsizeof (v ))
// # DEFINE _ addressof (V) (& reinterpret_cast <const char &> (v ))
// # DEFINE _ intsizeof (N) (sizeof (n) + sizeof (INT)-1 )&~ (Sizeof (INT)-1 ))
// # DEFINE _ crt_va_arg (AP, t) (* (T *) (AP + = _ intsizeof (t)-_ intsizeof (t )))
Note:
1. The va_start macro depends on the first function address to obtain the address of the next function. That is why a function with an indefinite parameter requires at least one parameter.
2. You need to interpret the number of function parameters by yourself. If the first parameter definition in printf can obtain the number of subsequent parameters, or the last parameter must be defined.