10 C Language Tips to Save Beginners 180 Days of Trouble!

Click the blue text
10 C Language Tips to Save Beginners 180 Days of Trouble!
Follow us

Due to changes in the public account’s push rules, please click “View” and add “Star” to get exciting technical shares as soon as possible.

Source from the internet, please delete if infringing

10 C Language Tips to Save Beginners 180 Days of Trouble!

Tip 1: Avoid Using “GOTO” Statements

Over twenty years ago, when computer programming was still in its infancy, program flow was controlled by “GOTO” statements. Such statements allowed programmers to jump from the current line of code directly to another segment of code. List 1 provides a simple example.
10 C Language Tips to Save Beginners 180 Days of Trouble!
List 1 Using GOTO Statement
Eventually, programming languages began to introduce the concept of functions, which allowed for code segmentation. If completed, there is no longer a need to use GOTO statements to represent code segmentation. After a function call, it will return to the next instruction. List 2 serves as an example. This approach improves program structure and enhances readability.
Since then, this has been regarded as the correct way to write programs. Just seeing or thinking about the GOTO statement makes software engineers recoil with instinctive disgust. One of the main reasons is that a program filled with GOTO statements makes it very difficult to grasp the focus, making it inconvenient for understanding and maintaining the program.
10 C Language Tips to Save Beginners 180 Days of Trouble!
List 2 Controlling Flow with Functions
Tip 2: Use FOR(;;) or While(1)
If GOTO statements are outdated, how should one create infinite loops in programs? This is a question some hardware engineers may wonder. After all, previously, it was done by creating a GOTO statement and then returning to the main statement. The solution is to utilize the existing loop statements in C language: for and while (Lists 3 and 4).
10 C Language Tips to Save Beginners 180 Days of Trouble!
List 3 Using an Infinite For Loop
10 C Language Tips to Save Beginners 180 Days of Trouble!
List 4 Using an Infinite While Loop
The loop conditions in the lists are relatively simple. The for loop simply uses a condition statement without conditions. On the other hand, the while loop executes the statement if true, which is equivalent to any non-zero value of the condition.
Tip 3: Use Appropriate Conditional Statements
Apart from code readability, the execution time of a program also primarily depends on the type of conditional structure chosen when making decisions. Many hardware engineers are familiar with the use of simple if statements. However, sometimes engineers may not realize that if the first condition is not correct, they can also use else or else if statements. This can save processor time without having to evaluate another condition statement.
In the first half of the code shown in List 5, if the value of Var is 1, the code will still check if Var is 0. In the second half of the code using the else statement, only the first statement is evaluated, and then it continues with the following code, thus saving clock cycles and making the code clearer.
10 C Language Tips to Save Beginners 180 Days of Trouble!
List 5 Using If/Else Instead of Just If
If/else If/else statements may not always be suitable. If you need to check several possible conditions, a switch statement may be more appropriate. This way, the processor can evaluate the statement and choose the next action from a list of answers without continuously evaluating a set of conditions. The example shown in List 6 is similar to that in List 5.
10 C Language Tips to Save Beginners 180 Days of Trouble!
List 6 Using Switch Statement
The implication of the above examples is to make the selection of conditional statements more open to choose the most suitable statement. This approach simplifies program structure, facilitates understanding of program flow, and reduces extra clock cycles for the processor.
Tip 4: Avoid Using Assembly Language
The natural language of microprocessors is assembly language instructions. Programming in low-level machine language may provide more efficient code for the processor. However, humans are not born to know this language, and experience shows that writing in assembly language can lead to misunderstandings. Misunderstandings can lead to improper maintenance and, worse, may cause bugs throughout the system.
The general recommendation is to avoid using assembly language. In fact, most compilers now can compile very efficient code. Developing in high-level languages like C or C++ can achieve a more organized structure, making it easier to understand and maintain, resulting in better overall code. List 7 provides an example comparing the assembly code and C code used to increment a 32-bit variable.
10 C Language Tips to Save Beginners 180 Days of Trouble!
List 7 Incrementing a Variable with Assembly and C Code
Assembly C code Of course, there are still some occasions where using assembly language is appropriate, but these occasions are relatively rare. The first recommended occasion is developing bootloader programs. In this case, optimizing the speed of a decision during startup (starting an application or bootloader) may be necessary. At this point, branch determination using assembly code may make sense. Another occasion is developing a control loop running on a DSP with strict timing requirements.
To achieve every clock cycle in the device, coding a control loop in assembly language makes sense. If the current task is suitable for assembly, ensure it is properly archived for reference, so that future developers (or future versions) will understand the purpose of the code.
Tip 5: Make Full Use of Modularity
One of the most common experiences for me is that a new project initiated by hardware engineers is often a chaotic code organization. We often find that the code consists of a single main module with over 25,000 lines of code. In these applications, everything is global, with few functions, and GOTO statements running throughout the code structure. Fifteen years ago, this was considered normal, but it is no longer applicable!
C language programming allows engineers to break the code into independent functional modules, simplifying code navigation while enabling engineers to use encapsulation and other object-oriented techniques. Code can be organized into logical modules, which makes sense. Although it may take a bit of time (a few minutes) initially, in the long run, it will save many long nights and a lot of debugging troubles!
Tip 6: Write Layered Code Instead of Spaghetti Code
Beningo is an Italian name, and like many Italians, I have an unabashed love for Italian pasta. When comparing pasta to software, I think of two types of pasta: spaghetti and lasagna. Spaghetti is messy, with noodles intertwined, resulting in no structure whatsoever. Writing unstructured code is very much like spaghetti: take a bite, and you have no idea which part you’re eating. The other is lasagna! This pasta is layered and structured. Layered code is not only easier to understand but also allows for the removal of one layer and the addition of a new layer, essentially enabling reusability and ease of maintenance. Figure 1 provides a simple software module example using a layered code model.
10 C Language Tips to Save Beginners 180 Days of Trouble!
Figure 1 Layered Software Model
Driver Configuration
Application Configuration
Application
Driver Library
Hardware
Tip 7: Use Descriptive Variable Names
Writing large software that is easy to understand and maintain has many obstacles, one of which is the naming conventions of variables. To shorten variable names, developers often create shorter, obscure mnemonics, symbols that only they can understand. Modern languages allow a variable name to contain hundreds of characters. To keep things clear and straightforward, a “straightforward” approach is better than others. Therefore, having a variable name that is self-explanatory benefits not only developers but also future maintenance teams. List 8 provides an example.
10 C Language Tips to Save Beginners 180 Days of Trouble!
List 8 Naming Variables
Tip 8: Use #pragma Statements Sparingly
In C language, there is a special #pragma statement. These statements typically deal with non-standard syntax and features and should be avoided as much as possible because they are non-standard and cannot be ported from one processor to another. Some compilers may require the use of such statements to accomplish certain tasks, such as defining an interrupt service routine. In such cases, there may be no choice but to use #pragma statements.
If possible, place all #pragma statements in one module or a few modules. This helps ensure that when porting the code, only a few places need to be updated instead of the entire codebase; additionally, this will help prevent the confusion brought by the first compilation of the ported code.
Tip 9: Errors Are Often Not as Simple as They Appear
Tip 9: Errors Are Often Not as Simple as They Appear
When debugging a C program, one alarming trap is compiler errors. Due to the complexity of compilers, when an error is detected, it is often located elsewhere in the program rather than at the position indicated by the compiler. This mainly relates to the steps the compiler takes to generate the program. The types of errors are usually consistent, and among the errors that engineers can discover, 90% have the following root causes:
• Be cautious of missing #include files. This may allow the program developer to see perfect lines of code, but due to the absence of necessary header files, the compiler marks it as an error, indicating something is undefined.
• Be cautious of missing semicolons. One of the most common mistakes when writing C code is forgetting to add a semicolon at the end of a statement.
• Be cautious of missing parentheses. Omitting parentheses is another common mistake during code writing, either due to carelessness or a typing error that generates an erroneous character.
• Be cautious of missing commas. It’s easy to forget commas in complex definitions! Generally, when a strange compilation error dialog pops up, check the content that has been compiled before that line. The error is likely located there! It may appear on the line above, in the middle, or in a completely different file. Don’t give up! With some experience, resolving these tricky issues will become second nature.
Tip 10: The Number of Lines of Code Written by Great Programmers Is Not Necessarily Fewer
There is a common misconception that a great programmer writes fewer lines of code to solve problems compared to a regular programmer. Don’t fall into this erroneous idea! A great programmer usually possesses a solid coding foundation with clear structure. Variable naming and encapsulation are just right, and there are almost no global variables in the system. Functions should remain short and effective. If the code looks messy and requires more lines to make it clearer, then feel free to write more lines! You can look online to find code that has won the award for the most chaotic C code as a cautionary tale. The code written by great programmers is concise, easy to understand, and maintain, and the number of lines of code is not the least (Figure 2)!
10 C Language Tips to Save Beginners 180 Days of Trouble!

If you are over 18 years old and find learning 【C Language】 too difficult? Want to try another programming language? Then I recommend you learn Python. There is a limited-time free Python beginner course worth 499 yuan, limited to 10 places!



▲ Scan the QR code - Get it for free



10 C Language Tips to Save Beginners 180 Days of Trouble!
Click to read the original text for more information

Leave a Comment