Turn: The programming styles and design ideas learned from the C programming Language

Source: Internet
Author: User
Tags strcmp

Here's a very good book.:http://www.cnblogs.com/xkfz007/articles/2566424.html  reading is not an end, the key is to think.   Very early on the water wood to see someone recommended "the C programming Language" This book, has not seen, the beginning of one months to concentrate on reading a bit, and seriously do after-school exercises. Read to harvest a lot, there are two main points: first, deepen their understanding of some basic knowledge and sentiment; second, from the middle school to some good programming style and design ideas, although these things look humble but chew is still worth learning. The following from four aspects to do a small summary, the level of limited, coupled with just read the first time, inevitably there are omissions and errors, very welcome to criticize the supplement. = = = Reading sentiment ====== design ideas ====== programming style ====== Classic routines ===  reading sentiment   First of all, I have to say that this is worthy of the master of the work (on the Internet as the C Bible), a thin book can not be thin, more than 200 pages, It covers most of the essence of C; It is worth mentioning that the book only priced 30 yuan, which in computer books can be said to be very cheap, and the market is flooded with a variety of C-language tutorials in the cost-effective form of a great contrast. However, I have to admit, personally feel that this is not an introductory book, it is necessary to read a certain basis. Second, talk about the writing style of the book and suggestions for reading. The book is not a space to list a grammar and knowledge points, but in a case-driven, most of the knowledge point is a small program to explain, so the proposed reading process will also be used as exercise to do, and then compared with the program given by the author, will find their thinking is how not meticulous, consider the problem is how deficient, When you slowly "go on", write a similar to the author and even feel better than the answer he gave, the sense of interest and accomplishment will encourage you to a virtuous circle.   Maybe some people will say that the example in the book is very simple, but I would like to say that although very simple, but each example is a classic, and can effectively govern above his business, in the process of writing code, too much detail to let people clairvoyant, can be Zhu Ji Nanxiong everywhere, some of the book's exquisite program section will make people feel: Aha, The original is so, originally can also write. This is a place where you can understand how many things you don't know before you read them.   Finally, let's talk about what this book contains in less than 300 pages. In the book from the classic Hello World, can be said to be hand-written and tell the C language of most of the syntax, not only that, but also to achieve a two-point search, Fast row, Hill sort (This implementation than our data structure to learn more clever), linked list, binary tree, hash these important data structures and algorithms. Most of the routines in the book will not only teach you about C, but also how to write efficient andEasy-to-read code, can let you understand some of the underlying design ideas, such as getchar,strcpy,fopen,printf, such as the implementation of many library functions are embodied, to help you explore the source, traced back. In addition, the book also contains a number of system call interface, the compiler principle (a recursive descent of the syntax analysis, this part did not understand, but also to read AH) implementation.   In a word, this book is worth a look. =================================================== Design Idea This part mainly summarizes the design ideas involved in the implementation of some library functions, which can be used as a reference     macro to replace the simple function. , avoid the overhead of function calls (note the side effects of avoiding macros, which are prone to errors, for example), such as GetChar, Putchar, and so on, to avoid the overhead of frequent calls to functions when processing characters macro. #define MIN (A, a) ((A) < b A b div>least = MIN (*p++,b);((*p++) < b P B div>     Storage Allocation Management book about this two Example, one is the storage space management in the form of a fixed size array that is determined at compile time, and the other is the design idea of the database function malloc. About storage management in the form of stacks here, please refer to Chapter 5.4, which focuses on the design concept of malloc.   Although the distribution program allocates storage space for different objects, there is only one storage allocation program in the program, but there are several types of requests to handle, in which case there are two problems: 1. How can I meet the alignment requirements of various types of objects on most machines? 2. What kind of claims can be used to enable the assignment program to return different types of pointers to handle different types of requests? In this respect, the drawbacks of stack storage management are immediately apparent.  malloc's design idea is a clever solution to these two problems. In alignment, it uses Union (union) to meet alignment requirements at the expense of some storage space. In the second aspect, the type of the return value of malloc is void*, so that when you call malloc, the type of pointer that is required to perform the type is turned on, so malloc does not need to identify what type of memory to request, it only cares about the total number of bytes in memory.   In addition, malloc does not allocate space from a fixed-size array that is determined at compile time, but is required to apply to the operating system and is organized in the form of free block lists.       Buffers   I am nowThe idea of a buffer in the sense of gray is often important, the design of buffers can reduce and avoid a lot of tedious operations, common is frequent IO operations. This is especially true when I write a search engine crawler when I write Web pages crawled into a Web library, and this book's routines once again deepen my understanding of the buffer zone.   Sometimes, the program is not sure if the input you have read is enough, unless you read some more inputs ahead of time. For example, reading some words from the input line conforms to a number (perhaps the integer may be a floating point type) is one example: first read and remove the leading blank, and then one character to read, but we do not know when the read stop, such as the input character "1314.521ahathinking", We have to read the character ' a ' before we know the number has been read. At this point, the last character is not the number that is currently being read, and the next read cannot read from character A. At this point, we need to press it back into the input, for the rest of the code is equivalent to not read the character, how to press back into the input? Sharing a buffer is a good way to read a character if there are characters in the buffer, if there is a read, if it is not read from the input. Implementations are shown in Chapter 4.3 in Getch and ungetch.   Similar to another example, is Chapter 8.5 in the implementation of GETC and PUTC: read from a file or write a character, the source code is not every time from the file read and write, so the IO operation is too frequent, but each read or write a chunk of content into the buffer, Each time the number of characters remaining in the buffer is checked first, if >0, the next character pointer is returned, otherwise the buffer is filled.   It's worth mentioning that the idea of a buffer is a bit like a stack of storage management, and that large array of stacked storage is equivalent to a pre-opened buffer.       Function design   about function design, the core question is how to break down the problem to be solved, write out each function that has independent function, by practicing the routine in the book (mainly Chapter 5 and Chapter 6), You can not only realize that the rational decomposition of the problem will make the program look structured, clear logic, but also feel the benefits of the module independence, as long as the interface is well designed, write each function does not need to consider too much other things, when all the Decomposition function function is completed, You will find that it is divide-and-conquer to feel a complex problem.   In addition, the design of each function should be considered carefully. such as the implementation of the Getline function, read the process of thinking, if this function allows you to design, how would you design? How are function parameters designed? How is the return type defined? Is it possible to return a void type as usual or to design a more reasonable one for its future usereturn type? How should function function logic be implemented? Is it up to read the data or to consider removing the leading whitespace from the input line? Is there an unexpected situation? For example, what if I read a blank line? How is the program structure arranged? Do you want to write or consider that the program structure can be expressed more succinctly? How to make the program more refined? All these, in fact, we need to think carefully, not simply a function of the problem, as previously said, although simple, but each example is very classic, it is worth our learning, more important is to think!       Two forks   count the number of occurrences of all words in the input without knowing the word list, and print in descending alphabetical order and word frequency, respectively? How would you design it?  chapter 6.5 Routines let you feel the strength of the two-fork tree, not only convenient to find, and the word itself is placed in the correct position, and the record of each word node position pointer makes it easier to sort by the frequency of words. Dry goods, it is worth carefully to ponder.       Hash   As you know, macros are replaced with text extensions during the precompilation phase, but do you know how the compiler implements macro processing? Or what is the core mechanism of the macro processor implementation? Similarly, how is the compiler's symbol Table Manager implemented?   Yes, that's the hash, Chapter. 6.6 Table Lookup routines give us a good idea, and a deeper understanding of the design of hashing will help solve a lot of problems, not to be bothered with, perhaps, when used to be unexpected, It's exactly what makes us feel so simple that we have something that makes us sound so complicated.       Variable parameter list design   This book speaks printf when it comes to how variable parameter lists are implemented, feel this should be understood, now use not, perhaps the future work will use it, there is a concept first. Magical use of       bit fields   when some information needs to be encoded, such as encoding the state of a variable (whether it is a keyword, whether it is a static chapter 6.9), The status of the file pointer is encoded (is the state of the read or write, whether to reach the end of the file, whether an error chapter 8.5), etc., we often define a location corresponding to the relevant bit of the "Shield Code" collection, or use a bit field to integrate several attributes into an identity variable to record, This saves storage space (Chapter 6.9). Once this is defined, a bitwise operation can be used in the program to validate the associated property value.   This type of design ideas used in the library is very much, we should be familiar with and learn to use.       MostAfter listing the next few classic questions   through their implementation to understand the problem solving algorithm design ideas, the following topics in the classic routines have corresponding.   variable length text line sorting (pointer array), known word count frequency (binary), unknown word list statistics frequency and alphabetical order (binary tree), unknown word list statistics frequency and print in descending order (binary tree, sort), table finder (hash, linked list)  ======== ===========================================  Programming Style   This section lists some of the small styles, small habits, and every little thing that a person has learned after reading a book. It is best not to use abrupt constants in the   program, and to use macro definitions and annotations to make it easier for others to read them; In addition, in the macro definition, if it is an expression, preferably surrounded by parentheses (), if it is a block of statements, it is best to use the do {} and (0). #define MAXWORD 100//row allows the maximum number of characters to enter # define BUFSIZE 1024#define EOF ( -1)   character variables are represented by integer types, such as int c; Because character variables are stored as integral types, using integer representations can also avoid unnecessary problems. When an int ch;scanf ("%c", &ch);  function parameter is passed an array, the formal parameter can be defined directly as a pointer type, because the array is passed as a parameter by the incomplete type to the pointer type. void Test (char s[], int n); It is directly defined as void Test (char *s, int n) to write efficient, refined code;  an arithmetic operation that integrates arrays, pointers, and addresses, as in the following example (you can try to write some classic library functions such as string handling functions strcpy, strcmp, etc., memory Operation function Memset, etc.), this idea is mainly reflected in the loop operation of the array elements. For more error-prone and overlooked areas, see Blog: Arrays, pointers, and address arithmetic: A classic little problem char * strcpy (char * s1, const char * s2)     {   &N Bsp    char * s = s1;        while (*s1++ = *s2++);        return s;    }  If a dynamic application is used, it is a good practice to decide whether or not to apply for success after applying char * ptr;if ((ptr = (char *) malloc (nbytes))! = NULL) {...}   Understand that register variables register and inline are "recommended" keywords, and compilers do not necessarily do so. Note: Only local automatic variables and formal parameters can be defined as register variables, and for cyclic control variables and repeated use of variables in the loop body can be defined as register variables, the loop count is the best candidate to apply register variable   Utilization bit operation, for example, in the multiplication method, take the mold operation, see the following example. In this regard, see the article binary thinking series i = 879/16; Contrast i = 879 >> 4;j = 562 32; When comparing J = 562 & (0x1f);  writing a recursive function, the static variable is a useful thing to avoid the passing of some parameters. This is not an example of it, when programming encountered recursion slightly to this aspect of thinking about the line  ===================================================  classic routines   Here in the Chinese version for reference, the list of routines is only a personal view of the classic part, many non-listed exercises are also worth doing, to understand some of the basic things (such as the first chapter of the 1-20 to help understand the tab, 1-23 to understand the similar "ab\" CD "such as a special string, etc.)." &NBSP;P21 read a line of String functions getline and subsequent improvements in the book  p22 exer-1-19 anyway string reverse function, this function is very simple, but it has a not so simple extension version (see Blog about reverse Words thinking and three kinds of solutions), at the first on the water wood to see someone recommended K&r, but also because of this extended version of a test  p38 exer-2-4 function Squeeze, see the comparison of three ways to achieve  p41 Exer-2-9 the number of binary 1, the Notebooks Bo provides three methods as a comparison, the key is to do the extension, in-depth understanding of some of the techniques of bit operation and the derived important data structure BIT-MAP implementation (see blog bit index), about bit operation I made a small summary: binary thinking series of articles &NBSP;P51-P52 Routines Atoi and ItoaFunctions, as well as subsequent improvements, the two functions need to consider more details, the implementation of the Shellsort function  p66 function Getop function and the getch and Ungetch functions used, the latter two functions are practical  p74 function qsort implementation, To be able to write the proficiency of the &NBSP;P90 library function strcpy,strcmp implementation and after-school exercises  p92 variable long text line of the implementation of the order, this should be very classic, clever use of pointer array to sort text lines  p102 function pointer use, According to the different requirements of sorting design different function interface  p119 known Word table, statistical keyword number, the use of pointers to achieve, dry, by the way review binary find  p121 self-reference structure of the routine, unknown Word table, Statistical frequency, alphabetical order, binary tree skillfully used  p125 exer-6-4 Unknown Word table, statistical frequency, according to the frequency of descending print, binary tree and the combination of sorting  p125 Chapter6.6 table to find, realize the idea of linked list, hash; Implementation mechanism of symbol table management of macro processor or compiler   Note: Regarding those points of knowledge (such as the distinction between declarations and definitions). #define与const及typedef的区别等), this article does not list, need in the coding process to experience.   Welcome criticism to Add.

Turn: The programming styles and design ideas learned from the C programming Language

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.