In the C programming language, the printf function is used for standard output.
Int printf (const char * format ,...);
In the printf function declaration, "..." represents a variable parameter.
Printf ("floats: % 4.2f % +. 0e % E \ n ", 3.1416, 3.1416, 3.1416); printf (" Width trick: % * d \ n ", 5, 10 );
So how to implement variable parameters?
Recently, I saw an implementation while reading the Linux0.12 source code. Below, I will provide a demo program.
# Include <iostream> using namespace std; typedef char * va_list; # define _ va_rounded_size (TYPE) (sizeof (TYPE) + sizeof (int)-1) /sizeof (int) * sizeof (int) # define va_start (AP, LASTARG) (AP = (char *) & (LASTARG) + _ va_rounded_size (LASTARG) # define va_end (AP) # define va_arg (AP, TYPE) (AP + = _ va_rounded_size (TYPE), * (TYPE *) (AP-_ va_rounded_size (TYPE) void print_args (int args ,...) {va_list ap; // before accessing any unnamed parameters, you must use the va_start macro to initialize the ap once va_start (ap, args); printf ("% d \ n", args ); printf ("% d \ n", va_arg (ap, int); printf ("% s", va_arg (ap, char *)); // va_end (ap);} int main (void) {int arg = 2; int args1 = 1; char * args2 = "abcdefg"; print_args (2, args1, args2); return 0 ;}
SetBreakpoint.
First, check the memory address of the args parameter:
+ & Args0x0028f71cint *
Now, let's check the memory at 0x0028f71c:
0x0028F71C 02 00 00 00... 0x0028F720 01 00 00 00 00... 0x0028F724 08 58 cd 00. X ?.
Obviously, the four bytes at 0x0028f71c are 0x00000002, that is, the arg parameter in the main function;
The four bytes at 0x0028f720 are 0x00000001, that is, the args1 parameter in the main function;
The four bytes at 0x0028f724 are 0x00cd5808, which is a memory address;
0x00CD5808 61 62 63 64 abcd0x00CD580C 65 66 67 00 efg.
Continue to check the memory at 0x00cd5808. We can see that it is "abcdefg \ 0 ".
With the above basics, we should be able to understand the va_start, va_end, and va_arg macros. In fact, it is the operation on the address and forced type conversion. The printf function also uses the preceding three macro functions to implement variable parameters.
Implementation principle of variable C parameters