C language programming suggestions and techniques are also applicable to the learning of microcontrollers.

Publisher:chwwdchLatest update time:2022-12-15 Source: zhihu Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

We encourage clear philosophical thinking when programming rather than giving hard and fast rules. I don't expect you to agree with everything, as they are just opinions, and opinions change over time.

However, if I had not put them down on paper until now, these opinions based on many experiences have been accumulating in my mind for a long time. So hopefully these insights will help you understand the details of how to plan a program. (I haven't seen a good article on how to plan the whole thing, but it could be part of the course.) If you can find their idiosyncrasies, that's great; if you don't agree with them, that's also great. But if it inspires you to think about why you disagree, that would be even better.

Under no circumstances should you program the way I describe it; try to complete the program using the programming method you think is best. Please do this consistently and without mercy.

Typesetting issues

A program is a publication. This means that the programmers will read first (perhaps you yourself days, weeks, or years later), and the machine will read last. The happiness of the machine is that the program can be compiled. The machine does not care how beautifully the program is written, but people should keep the program beautiful. Sometimes people are overly concerned: using a beautiful printer to mechanically print out beautiful output, and these outputs are just all the prepositions highlighted in bold fonts in English text, which are details that have nothing to do with the program.

Although many people believe that programs should be as described in Algol.68 (some systems even require programs to be written in this style), clear programs will not become clearer because of such presentation, and it will only make bad programs becomes more ridiculous.

Typographic conventions have always been crucial to clear programs. Of course, the most useful thing we all know is indentation, but when ink obscures the intent, it takes control of the typography. So even if you stick to plain old typewriter output, it's time to be aware of silly typography. Avoid over-embellishment, such as keeping comments concise and flexible. Speak neatly and consistently through programming. Then look down.

Variable naming

For variable names, length is not the value of the name, clarity of expression is. Global variables that are not commonly used may have a long name, like maxphysaddr. The array index used for each row in the loop does not need to be named more specifically than i. Selecting index or elementnumber requires typing more letters (or calling a text editor) and obscures the details of the calculation. When variable names are long, it's hard to understand what's going on. In part this is a typography issue, see below

vs.

In real-life examples the problem gets worse. So just treat the index as a symbol. Pointers also need sensible notation. np is just a mnemonic for pointer nodepointer. If the naming convention is followed consistently, it is easy to deduce that np stands for "node pointer". More on that in the next article.

At the same time, consistency is also extremely important in other aspects of programming readability. If the variable is named maxphysaddr, do not name the variable in the sibling relationship lowestaddress.

In the end, I prefer "minimum length" but "maximum information content" naming and let the context fill in the rest. For example: global variables have little context to help them understand when they are used, so their names need to be relatively easy to understand. Therefore I call maxphyaddr as a global variable name, np is not necessarily a NodePoint for pointers defined and used locally. It's a matter of taste, but taste is about clarity.

I avoid embedded capital letters in names; they are too awkward for reading comfort and can be as annoying as bad typography.

Use of pointers

The C language is unusual in that it allows pointers to point to anything. Pointers are sharp tools, and like any such tool, they can be delightfully productive when used correctly, but they can also be extremely destructive when used incorrectly. Pointers have a bad reputation in academia because they are so dangerous that they suddenly become terrible. But I think it's a powerful symbol that helps us express ourselves clearly.

Think about it: When there is a pointer pointing to an object, for that object, to be precise, it is just the name and nothing else. It sounds trivial, but look at the following two expressions:

The first one points to a node, the second one evaluates to (so to speak) the same node. But the second form is a less understandable expression. Explain here, because we must know what node is, what i is, and what the rules are related to i and node and the surrounding programs. The expression in isolation does not indicate that i is a valid index of node, let alone the index of the element we want.

It would be easy to go wrong if i, j, and k were all indices into the node array, and not even the compiler would be able to help find the error. This is particularly error-prone when passing parameters to a subroutine: the pointer is just a single parameter; but the array and index must be considered one in the receiving subroutine.

Evaluating to the object expression itself is less observable and error-prone than the address of the object. Proper use of pointers can simplify your code:

If you want to remove the type of the next element, you can

i is moved forward, but the rest of the expression must remain unchanged; with pointers, only one thing needs to be done, which is to move the pointer forward.

Take typography into consideration as well. For working with continuous structures, using pointers is more readable than using expressions: less ink is required, and the performance cost of the compiler and computer is small. A related issue is that the pointer type affects the correct use of pointers, which also allows some useful error detection at the compile stage to check that the array sequence cannot be separated. And in the case of structures, their label fields are hints of their type. therefore

It's enough for people to understand. In the case of an indexed array, the array will have carefully chosen names and the expression will be longer:

Also, as the examples get larger and larger, the extra characters are even more annoying.

In general, if you find that your code contains many similar and complex expressions, and the expressions evaluate to elements in a data structure, judicious use of pointers can eliminate these problems. think about it

It looks like using a compound expression to represent p. Sometimes it's worth using a temporary variable (p here) or extracting the operation into a macro.

process name

Procedure names should indicate what they do, and function names should indicate what they return. Functions are usually used within expressions like if, so they are more readable.

It is not very helpful, because it cannot be inferred whether checksize returns true when it is an error or whether it is not an error. on the contrary

Make this clear and less likely to go wrong in the future in regular use.

Comment

This is a delicate issue that requires your own experience and judgment. For a few reasons I tend to err on the side of clearing comments. First, if the code is clear and standard type names and variable names are used, it should be understandable from the code itself. Second, the compiler cannot check comments, so it cannot guarantee accuracy, especially after the code has been modified. Misleading comments can be very confusing. Third, typesetting issues: comments can make the code cluttered.

But sometimes I write notes, like the one below, just to use them as an introduction. For example: to explain the use and types of global variables (I always write comments in huge programs); to serve as an introduction to an unusual or critical procedure; or to mark a section of a large-scale calculation.

Here is an example of bad comment style:

There are worse ways to do it:

Don't laugh at it yet, wait until you see it in reality.

With the exception of perhaps crucial sections such as declarations of important data structures (comments on data are usually more helpful than those on algorithms), "cute" formatting of comments and long comments need to be avoided; basically it is best Just don't write comments. If the code needs to be explained by comments, the best approach is to rewrite the code so that it is easier to understand. This brings us to complexity.

the complexity

Many programs are overly complex and more complex than the problems that need to be solved effectively. Why is this? Most of it is due to bad design, but I'll skip this question because it's so big. However, programs are often complex at a micro level, and these can be addressed here.

  • Rule 1: Don’t determine where your program will spend its time. Bottlenecks appear in unexpected places. Until you know where they are, don't try to second guess and run faster.

  • Rule 2: Measure Don't optimize speed without measuring the code. Unless you find the most time-consuming part of the code, don't do it.

  • Rule 3: When n is small (and it usually is), fancy algorithms run very slowly. Fancy algorithms have large constant level complexity. Don't use fancy algorithms until you're sure n is always large. (Even if n becomes large, rule 2 is preferred). For example, for common problems, binary trees are always more efficient than stretch trees.

  • Rule 4: Fancy algorithms are more likely to have bugs than simple algorithms, and are more difficult to implement. Try to use simple algorithms and simple data structures.

The following are data structures used in almost all real programs:

  • array

  • linked list

  • Hash table

  • Binary tree

Of course, we must also be prepared to flexibly combine these data structures, such as a symbol table implemented with a hash table, where a hash table is a linked list composed of character arrays.

  • Rule 5: Put data at the core If you choose the appropriate data structures and organize everything logically, the algorithm will always be self-explanatory. The core of programming is data structures, not algorithms. (Refer to Brooks p. 102)

[1] [2] [3] [4]
Reference address:C language programming suggestions and techniques are also applicable to the learning of microcontrollers.

Previous article:I have a microcontroller, do you have wine?
Next article:Summary of commonly used algorithms for sensor data in microcontroller development

Latest Microcontroller Articles
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号