The secret of C language prinft Function
Starting from the first program Hello World in C language, almost all C programs written so far have its appearance.Quasi-output functionPrintf. It seems that the uniqueness of the printf function is not noticed.
1. Variable Length Parameter: Incredible
You may not note that the parameter of the printf function is a variable-length parameter.
Printf ("Hello World! ");
Ptintf ("% d", number );
Printf ("Two number: % d", number1, number2 );
First, I tried to resolve this issue from the knowledge related to the function. At last, I could only draw a conclusion: Incredible.
2. Common formats of printf:
Printf (char * format, arg1, arg2 ...);
The format is called a formatted string. It contains common characters and Conversion characters.. During output, normal characters are copied to the output stream intact. Conversion characters are used to control the output mode of parameters.
Arg1, arg2... is a list of parameters.
For example:Printf("Hello World! ");
The formatted string contains only common strings."Hello World! ", Then"Hello World! "Output as is.
Another example is: Printf("Two number: % d", number1, number2 );
Formatted string contains regular string"
Two number:
"And conversion string" % d ","Two number:"Original output. The conversion string is used to control the output of number1 and number2.
3. prinft Definition Format:
Int printf (char * format ,...)
The ellipsis... indicates that the number and type of parameters are variable.
Key: how to deal with the parameter table represented by.... It does not even have a name. The answer is a set of macro definitions in the standard header file <stdarg. h>. These macro definitions provide a way to traverse the parameter table. The va_list type is used to declare a variable, which references parameters of the parameter table in sequence. Va_start points the va_list variable to the first unnamed parameter. Va_arg returns a parameter in the parameter table and points the va_list variable to the next unnamed parameter. Based on a data type name, va_arg determines the type of the returned parameter and the stride of pointer movement. Va_end is used for cleaning.
4. Write your own printf function:
It is easy to implement a Myprintf. For the sake of complexity and emphasis, Myprintf does not implement its own int/double conversion. Its int/double conversion actually uses the printf conversion, therefore, stdio must be included. h, but don't worry about these irrelevant details. With Myprintf, how does printf use a variable-length parameter table, the working mechanism of printf is clearly displayed.