Do you really understand printf?

Source: Internet
Author: User

Since you entered the programmer's world, you began to write a variety of helloworld Based on books, with a big wave:

Printf ("Hello World! \ N ");

So a line of strings appeared magically on the console. The computer gave a warm greeting to how many young coolders were introduced into this magical world, even more than 58 cities ......

<Stdio. h>

Main ()
{
A = 0.5;
Printf ("float a is % f \ n", );
0;
}

* _ VALIDATE_RETURN (format! = NULL), EINVAL,-_ lock_str2 (buffing = retval = _ unlock_str2 (}View Code

As a result, we know that the key problem in printf is to pass in multiple parameters and how to parse and output the information. The parameter transmission is mainly completed by several macros: va_list, va_start, and va_end. The three macros are defined in stdarg. h is replaced, and the real definition is in vadefs. h:

  

Va_list is actually char *, which is used by the publisher. va_start (ap, fmt) locates the address of the first parameter, and va_end (ap) points the ap pointer to a null value to prevent the wild pointer problem. Next, we can see that the essence of the printf function is the three functions in the try block. Then let's go and see what's going on.

  

Step 2: The program pointer jumps to the _ stfbuf. c file and runs the _ stbuf (stdout) function.

This function initializes the buffer and prepares for subsequent conversion and printing. The buffer size is 4096 bytes. If the buffer is successfully executed, the return value is 1.

 

Step 3: Go to the _ output_l function in the output. c file:

This function is the core. First, we will set a lot of flag values, such as the floating point precision, the number of digits added to the front suffix, or something. I can't tell you exactly what each function is. Let's take a look at the following process. The while loop of the first row begins to parse the string. The value of format is "float a is % f \ n ", put a single character into ch, and then check the type below. For example, the ch value is f, which is a common character, so the state value is set to ST_NORMAL, run the following switch statement.

  

There are many status branches in the switch statement, such as ST_NORMAL, percent ST_PERCENT (which is special for printf), and ST_FLAG (Symbol. For common characters, the format pointer is directly written to the buffer. For each character written, the format pointer is shifted to the back. When % is parsed, the branch of ST_PERCENT is executed.

  

  

Then read the next character and find that it is f. Then find the branch of ST_TYPE and extract the data. Argptr is the pointer to the floating point a address. Extract data by double type and save it to tmp.

  

  

  

Step 4: After the data is extracted, execute the conversion function:

When the data is saved to tmp, You can execute the following function to convert numbers into strings and put them in buf. The key to printf is how to parse (or extract) parameters, finally, all the parameters are converted into strings and put into a buffer and output to the screen. The converted floating point is stored in text. sz of char * type. If you are interested, go to the convert function to see how to convert it ~ (For floating point, it seems that there is a function named DTOA, which is hard to remember)

  

After the work is completed, the output_l function returns the number of printed characters: 20. (You can count the output characters in the lower-end console and include line breaks)

 

Step 5: Write the string to the standard output stream:

Returned to printf. in c, run the _ ftbuf function, and then enter the flush function. The console prints the string to be printed only when the pointer points to the following position, our task is completed.

  

  

Okay, let's talk about why I want to write this article about printf. It is because of the cross-platform printf implementation problem in the recent project that the floating point number cannot be printed, I checked a lot of information and found no relevance. There are different opinions on the Internet. So I sent a question to stackoverflow, but it was a very unpleasant thing. Let's take a look. The first is my original question:

  

The next step is fun ~ :

  

Original post address: http://stackoverflow.com/questions/18746570/printf-cannot-print-float-double-correctly-on-the-screen

I did forget to set the parameters a, B, and c at first, but this does not affect the question itself. Obviously, the people who answered the question initially did not think about it, I don't even know how to write the printf parameters. I even post the question rules to me so that I don't need to spam the questions. I also say that I am confused about the reasons, I am helpless ~. So what I want to ask is: first, are the questions raised by others as you think? Second, if others are really second, will the code compilation and execution by the code area with no parameters written appear as described? The lower limit of the show is coming without carefully looking at other people's problems and Symptom descriptions ~ After I modified the question (I only added a, B, and c in printf) and replied to the Message one by one (I started with sorry without exception ), none of the lower limits of the previous show can be answered, and even their own opinions cannot be raised (what can I say? Haha !).

Why can't they answer the question? Only those who have actually done embedded cross-development will know the possible cause of this problem. During the porting work, they will often encounter problems related to printf, not just floating point printing. Okay, let's see what people actually know. There are two possible reasons for the answer. (I have blocked one answer from someone else, is the lower limit ~), The eyes of the masses are bright. From my debugging results in the project, it should be the first reason below: The Byte alignment problem of the task stack leads to the error of floating-point parameter passing; the second answer is also possible, but we did not add the following Macro during compilation. Decisive vote ~ :

 

  

 

  

 

In C Interfaces and Implementations, we also explained the implementation of printf, which has some improvements to the printf of the Standard C library. The Code should be reusable and robust, if you are interested, you can check it out.

Okay. Ask yourself, do you really understand printf?

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.