Opening Speech
As I have already written in the previous article, C language is not only fun but also unpredictable. Its thoughts are more profound and need to be understood. I read no less than 50 books on C language. I feel a little deeper when I read it all over again, but I still cannot fully understand the deepest thoughts behind it, just keep approaching it. Because of this, the following description will not be written in a fixed plain text format, but will display the process in dialog mode, so that the C language idea can be displayed more.
Format: Question (question) starts with Q: And answer (answer) starts with.
Q: What does the C helloworld version look like?
A: The name is hello. C:
#include <stdio.h>int main(){ printf("Hello World!"); return 0;}
Q: # What does the include statement mean?
A: It starts with #. It indicates the preprocessing process. Generally, it is not treated as a compilation process, but is processed by a separate Preprocessor. Because, from the perspective of source code compilation, inserting a header file into the final compiled code is really not consistent with the compiled source code.
Q: How can we feel the existence of a pre-processor?
A: General Compilation commands provide preprocessing options to view the source code after preprocessing.
[Windows-VS2010] You can use the cl.exe command to view pre-processed source code:
CL/P hello. c
A. hello. i. The content is as follows (because of space issues, you cannot upload all the content; otherwise, you cannot save it. The ellipsis omitted most of the Code ):
#line 1 "hello.c"#line 1 "d:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\INCLUDE\\stdio.h"..........................................................#line 739 "d:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\INCLUDE\\stdio.h"#line 2 "hello.c"int main(){ printf("Hello World!"); return 0;}
Q: The file is too long!
A: Yes, this is actually a disadvantage of C and C ++. # The method of inserting source code into the include may cause the compilation source code length to increase rapidly, this is also a reason for precompilation. You can also see the lines of the hello. C code, that is, the last few sentences. The lines above are the # include header file inserted code, which is really big and straightforward.
Q: What is the meaning of the last sentence of the hello. I file, line 2 "Hello. c?
A: # It starts with a symbol and is still the compiler instruction. It indicates that the current row is set to 2 and the file name is hello. c. because the previous # include <stdio. h> the contents of many other files are inserted,. in C, the second line is followed by # include <stdio. h> later, so you can reset the number of rows to correctly parse hello. the number of lines of code in C.
Q: How do I know that the/p parameter is pre-processed by the CL command?
A: Of course, CL /? Command to get help, and then find the required function parameters.
Q: Is it difficult to search for so many parameters?
A: You can think of the grep command in UNIX to filter strings. Of course, this requires cygwin support.
The above grep command is available only after cygwin is installed.
Q: Let's go back to hello. C. Must the main function have a return value?
A: Yes. In fact, this is a reflection of the layered thinking. Any application may eventually have a return value for the program that calls it to use, so here there is an int return value.
It is understandable.
Q: How can I check the return value of a program call?
A: [windows] in the command line, Echo % errorlevel % can be used to obtain its value.
[Mac] in the command line, you can use echo $? .
[Ubuntu] is the same as [Mac].
For example, the hello.c code is compiled into hello.exe,
CL hello. C:
Generate hello.exe and run it:
Print the return value using echo % errorlevel %:
We can see that the returned result is exactly the 0 following the return statement in the code.
Q: Can I return 0?
A: Of course. Modify the source code of Hello. C:
#include <stdio.h>int main(){ printf("Hello World!"); return 1;}
After re-Compiling and running, use echo % errorlevel % to get:
Q: What is the prototype of printf?
A: In stdio. H, we can see that its prototype is:
Q: Why is it so complicated? What is the purple part?
A: In fact, many prototypes have some additional texts. They do not make much sense during the compilation process. They are just comments or descriptions, it works in some specific situations, so you don't need to pay special attention to them for the moment.
For example, the macro definition of _ check_return_opt _ is:
Then go to _ check_return _, and you can see a macro definition similar to the macro definition, which is analyzed in sequence.
Q: The simplified prototype of the printf function is
int __cdecl printf(const char * _Format, ...);
?
A: Yes, it can be simplified
int printf( const char * _Format, ...);
Q: What is _ cdecl?
A: This is a function call method. There are also _ stdcall ,__ fastcall and so on. There are some differences between them. For example, in the function pressure stack sequence, parameters are preferentially stored in registers, by default, the C language adopts the _ cdecl method.
Q: Can the const in const char * _ format be removed?
A: Yes, but the const is used to indicate unchangeable variables. The printf function cannot change the string pointed to by _ format. This is a defensive programming idea.
Q: isn't the const in C ++ representing a constant?
A: Yes, but const in C indicates a variable, but cannot be changed. This keyword is different in C and C ++.
Q: for example.
A: for example, a variable modified with const in C language cannot be used as the number of parameters in a static array because it is a variable. In C ++, this is acceptable.
For example, modify the hello. C Code as follows:
#include <stdio.h>int main(){ const int size = 10; int arr[size]; return 0;}
Compilation error:
The error is because the size of a constant is required to indicate the size of the array.
Q: What if it is C ++?
A: Use Cl/TP hello. C to compile the hello. C code as C ++ code:
No error occurs.
Q: The source code is not hello. C, and the suffix is. C. How is it compiled as C ++ code?
A: This mainly serves the/TP parameter:
As you can see, the/TP command line treats all files as. cpp for compilation, that is, the hello. C code will also be compiled as. cpp.
Q: isn't the source code compiled by the compiler necessarily suffixed?
A: Of course, for the compiler, you only need to give the text. For the suffix, it is only possible to compile the code according to the specified type. You can specify
Code with a certain extension is compiled as a specific type of code.
Q: What are the three vertices in the prototype parameters of the printf function?
A: It indicates a variable parameter, that is, the number of parameters cannot be determined. It may be 1, 2, or more.
Q: Why is this design?
A: For the output function, the designer does not know how much to output, so it is implemented by the programmer. The Compiler only needs to obtain
Finally, convert the parameters to the internal processing function correctly.
For example:
printf("Hello World!"); printf("My name is %s", "xichen"); printf("My name is %s, age is %d", "xichen", 25);
Q: What does the printf function return?
A: It returns the number of bytes successfully output.
Source code:
#include <stdio.h>int main(){ int ret; ret = printf("abc"); printf(" ret is %d\n", ret); ret = printf("Hello World!"); printf(" ret is %d\n", ret); ret = printf("My name is %s", "xichen"); printf(" ret is %d\n", ret); return 0;}
Output:
Q: How can I calculate the number of bytes if there are Chinese characters in the string?
A: This is based on the number of bytes finally output by the terminal.
Open notepad in windows and write the following code:
# Include <stdio. h> int main () {int ret; ret = printf ("ABC China"); printf ("RET is % d \ n", RET); Return 0 ;}
It is saved in ANSI format, and ANSI is saved in localized encoding format;
[Windows7] the local language is in ANSI format by default. You can view the following information in the registry:
It is 0804,0804, which represents Simplified Chinese and is encoded as GBK.
Check again the encoding of the CMD output characters:
We can see that the encoding format is GBK.
Therefore, the above string "China" is output in GBK format, that is, a Chinese character corresponds to two bytes, that is, the total length of the string "ABC China" is 7.
Therefore, output:
Q: If I save the source code as utf8 and compile it, will the final result be changed?
A: Let's take a look.
Save the source code in utf8 format:
Compile hello. c again and run:
As you can see, the result is still 7.
Q: isn't the encoding format changed to utf8? do each of these two Chinese characters have three bytes? How is the number of output bytes 7? How does one think that each Chinese Character occupies 2 bytes?
Open the source code of Hello. c In utf8 format in hexadecimal format:
We can see that the two Chinese characters "China" occupy a total of 6 bytes, but why is the total number of bytes calculated after printf output not 9 but 7?
A: Of course, the encoding format of the source code and the encoding format of the string in the source code are not necessarily the same as the encoding format of the final output. As mentioned above, printf
The Return Value of the function is based on the actual number of bytes output by the terminal. The character encoding of the terminal is GBK, no matter what the encoding of the original code is, and the final output is not
There is an inevitable relationship, so the result is still 7.
Q: What is the encoding of the "ABC China" string in the executable file hello.exe?
A: Enable hello.exe in hexadecimal format,
We can find that the "China" string is saved in GBK encoding format. Here, we can understand why it has always been output 7.
Q: How can I change the encoding format of a cmd terminal?
A: This encoding format is also known as the code page. You can use the chcp command:
Enter chcp to get the current code page:
Changed to UTF-8 format, using chcp 65001:
Then run hello.exe. The result is still 7, but the "China" character is garbled.
I think you should know the reason.
Q: Can I use Unicode wide characters to output a string?
A: Yes.
The following code:
# Include <stdio. h> int main () {int ret; ret = wprintf (L "ABC % s", l "China"); printf ("RET is % d \ n ", RET); Return 0 ;}
[Windows-VS2010] output:
This code has not been tested on Mac or ubuntu. Because wprintf and % ls and % s are inconsistent in performance, you may need to modify the code.
Q: There are many output formats in the printf function, but if they are inconsistent with the data in the corresponding output format, what will happen?
A: Of course, some problems may occur, because the printf function dynamically parses the format string and then fills in the corresponding data.
% D format, but it is filled with a double data, which may lead to errors.
Q: for example:
#include <stdio.h>int main(){ printf("%d", 1.5); return 0;}
Why is there no compilation error in the compilation phase?
A: Because the compiler regards "% d" as a string and does not analyze the format, this is handed over to the implementation of the printf function. In fact, the responsibility for determining whether it is correct is handed over to the programmer,
If a programmer makes a mistake, the result may be followed by an error.
Q: How do I write the code output by the printf function parsing format?
A: This is based on the % sign in the string. This indicates that data in the corresponding format may be followed, for example, D. It indicates that it is an integer, fill in the corresponding data in the stack; if it is S,
It is to fill in the string, and so on; if the % symbol is not encountered, output as is.
A simple printf function that calls printf:
int __cdecl cc_printf( const char *format, ... ){ va_list argulist; int ret = 0; va_start(argulist, format); while (*format) {if(*format != '%'){ putchar(*format); ++ret; goto loop;}else{ ++format; switch (*format) { case 'c':{ int value = va_arg(argulist, int); ret += printf("%c", (char)value); goto loop;} case 's':{ char *value = va_arg(argulist, char *); ret += printf("%s", value); goto loop;} case 'd':{ int value = va_arg(argulist, int); ret += printf("%d", value); goto loop;} case 'o':{ int value = va_arg(argulist, int); ret += printf("%x", value); goto loop;} case 'x':{ int value = va_arg(argulist, int); ret += printf("%x", value); goto loop;} case 'X':{ int value = va_arg(argulist, int); ret += printf("%X", value); goto loop;} case 'u':{ unsigned value = va_arg(argulist, unsigned); ret += printf("%u", value); goto loop;} case 'f':{ double value = va_arg(argulist, double); ret += printf("%f", value); goto loop;} default:{ goto loop;} }}loop:++format; } va_end(argulist); return ret;}
Q: Let's go back to the question.
printf("%d", 1.5);
What will this output?
A: Compile and output:
Q: Why is this magic number output?
A: According to the ieee754 standard, the binary representation of double-precision floating point number 1.5 is:
00 00 00 00 00 F8 3f
As you can see, the values of the 4 lower bytes are all 0, while % d takes only 4 lower bytes, so the result is 0.
To conveniently print the values of each byte in double data, you can use the following union structure:
union double_data{ double f; unsigned char data[sizeof(double) / sizeof(char)];};
Q: Sometimes, the number of parameters after the printf format string exceeds the corresponding format in the format string. What is the result?
A: Write the following code:
#include <stdio.h>int main(){ printf("%d %d", 1, 2, 3); return 0;}
What is the output result?
Q: Why not output 2 and 3, or 3 and 2?
A: Check the Assembly:
Use the CL/FA hello. C command to compile and get the hello. ASM file:
; Listing generated by Microsoft (R) Optimizing Compiler Version 16.00.30319.01 TITLEF:\c_codes\hello.c.686P.XMMinclude listing.inc.modelflatINCLUDELIB LIBCMTINCLUDELIB OLDNAMES_DATASEGMENT$SG2637DB'%d %d', 00H_DATAENDSPUBLIC_mainEXTRN_printf:PROC; Function compile flags: /Odtp_TEXTSEGMENT_mainPROC; File f:\c_codes\hello.c; Line 5pushebpmovebp, esp; Line 6push3push2push1pushOFFSET $SG2637call_printfaddesp, 16; 00000010H; Line 8xoreax, eax; Line 9popebpret0_mainENDP_TEXTENDSEND
We can see that line 6 has four parameter stack operations, namely 3, 2, 1, and $ sg2637, $ sg2637 corresponds to the "% d" string.
At this time, you should have understood that this function has four parameters when calling printf ("% d", 1, 2, 3, however, the stack is pressed from the right to the left, and finally parsed.
In the "% d" string, the first format corresponds to the next element in the stack, that is, 1, and the second corresponding format data is found in sequence, that is, 2. Therefore, the final output
1 and 2.
Q: If the number of data formats in the first parameter in printf is greater than that of the subsequent parameter, what will happen?
A: Of course, according to the previous principle, when parsing the data format, one more data will be parsed from the stack, which may lead to subsequent running errors, because it is likely not
Programmer's intent.
Q: In some cases, the parameters following the printf function have several auto-increment or auto-increment operations. The final result is amazing. Is there any rule for this?
A: You mean, for example
#include <stdio.h>int main(){ int i = 1; printf("%d %d", ++i, ++i); return 0;}
The final result is probably not what you want, but this Code may give others Several guesses. Therefore, it is best not to write this code, or you can write it clearly.
Can understand the code; at the same time, this code is not very convenient to transplant, so we should try to write less such code.
Q: I heard that the printf function outputs data with buffering? What is the difference between this and outputs without buffering?
A: As a truth, the CPU speed is very fast and the peripheral operation speed is very slow. To avoid this speed gap, the CPU efficiency is seriously reduced. Therefore, many peripheral operations are buffered, including displays, keyboards, and hard disks. If the output is not buffered, it is immediately output and will not be processed by the buffer system.
Q: Why can't I see the buffer output?
A: It is easy to feel that the buffer prompts the input in cmd. You can enter a piece of data and press enter to process the data. This field indicates the buffer input.
For the buffer output, for example:
#include <stdio.h>#include <stdlib.h>int main(){ int i = 1; char *buf = (char *)malloc(512); if(buf) {setbuf(stdout, buf); } printf("hello"); printf("xichen"); return 0;}
Here, we applied for a 512-byte space and used the setbuf function to set the standard output buffer to Buf.
Then two strings are output to the standard output.
When you break a breakpoint on the printf ("Xichen") line and debug this line, you can find that there is no output on the console and there is still no output to continue running. The reason why there is no output is that they are buffered.
Then, modify the code and set the buffer to NULL:
#include <stdio.h>#include <stdlib.h>int main(){ int i = 1; setbuf(stdout, NULL); printf("hello"); printf("xichen"); return 0;}
Still in printf ("Xichen"); line breakpoint, debugging:
Run to the breakpoint, and view the console output:
It can be seen that the string of the previous code has been output, and there is no buffer.
Conclusion
Having written so much above, I don't know how easy it is to find the basic output function of printf. But I have learned the underlying information about its code and will have a deeper understanding of it,
The previous content is not necessarily applicable only to printf. Many internal implementations of the experiment can find some shadows from the above content. I hope these will help you.
Xichen
16:09:06