A perfect piece of code not only lies in finding a solution to a given problem, but in its simplicity, effectiveness, closeness and efficiency (memory ). The design code is more difficult than the actual execution. Therefore, every programmer should keep these basic things in mind when developing in C language. This article introduces 10 methods to standardize your C code.
1. If possible, use typedef to replace macro. Of course, sometimes you cannot avoid macro, but typedef is better.
Typedef int * int_ptr; int_ptr a, B; # define int_ptr int *; int_ptr a, B; In this macro definition, A is a pointer to an integer, B has only one integer declaration. Use typedef A and B as integer pointers.
2. In a logical condition statement, several items are always on the left.
Int x = 4; If (x = 1) {x = x + 2; printf ("% d", x); // output is 3}
Int x = 4; if (1 = x) {x = x + 2; printf ("% d", x); // compilation error}
Use the "=" value assignment operator instead of the "=" equal operator, which is a common input error. If the constant item is placed on the left side, a compilation error is generated, allowing you to easily capture your error. Note: "=" is a value assignment operator. If B = 1, the variable B is set to equal to the value 1. "=" equal operator. If the left side is equal to the right side, true is returned; otherwise, false is returned.
3. Make sure that the declaration and definition are static unless you want to call the function from different files.
Only static functions are visible to other functions in the same file. It limits other access to internal functions if we want to hide the function from the outside. Now we do not need to create a header file for the internal function. The function is invisible to others.
Static declaration of a function has the following advantages:
A) two or more static functions with the same name can be used in different files.
B) Reduced compilation consumption because there is no external symbol for processing.
4. Memory saving (memory alignment and fill concept)
Struct {char C; int I; short S;} str_1; struct {char C; short S; int I;} str_2; assume that one character requires one byte, short occupies 2 bytes and INT requires 4 bytes of memory. At first, we will think that the structure defined above is the same, so it occupies the same amount of memory. However, str_1 occupies 12 bytes. Does the second structure only need 8 bytes? How is this possible?
Note that in the first structure, 3 different 4 bytes are allocated to three data types, while in the first 4 bytes of the second structure, their char and short can be used, int can be adopted at the 4-byte boundary of the second one (a total of 8 bytes ).
5. Use an unsigned integer instead of an integer. If you know the value, it will always be negative.
Some processors can process unsigned integers faster than signed integers. (This is also a good practice to help self-documenting code ).