C language - how to write good code?

Hello, everyone, today we are going to learn how to write excellent code, mainly about the usage of assert and const .

 First of all, what kind of code is considered good code? Should meet the following requirements:

1. The code works fine

2. Few bugs

3. High efficiency

4. High readability

5. High maintainability

6. Comments are clear

7. Well documented

 Common coding skills:

1. Use assert

2. Try to use const

3. Develop a good coding style

4. Add necessary comments

5. Avoid coding pitfalls.

Today we mainly talk about assert and const.

assert

assert Is a C language standard library function, used to detect a certain condition when the program is running, if the value of the condition is false, it will make the program fail and terminate the operation, and output the error message to the stream  stderr .

assert The function of is to check whether a certain condition is true when the program is running. If the condition is not true, it means that there is an error in the state of the program. At this time, the execution of the program will be terminated and the error message will be printed. The robustness and reliability of the code can be improved by using it  assert . assert It is usually used to check certain unrecoverable errors in the program, such as internal logic errors, logic exceptions, etc. When these errors occur, directly stopping the running of the program allows developers to quickly locate the problem.

const

In the C language,  const keywords are used to define constants. const Can be used to modify variables, function parameters, function return values, etc.

Using keywords in variable declarations  const , you can define a constant whose value cannot be changed, as follows:

const int a = 10;

const Constants defined using  keywords will allocate space in the symbol table at compile time and give them a definite address, so they cannot be modified. const If you try to modify the value of a type constant in the program  , the compiler will find out and report an error at compile time.

Using keywords in a function definition or declaration  const , you can set a function parameter or a function return value as a constant, as follows:

int func(const int arg1, const int arg2);

const int func2(void);

These grammatical rules indicate that the function will not change the function parameters or return value, which can facilitate the caller to judge the logic behind the program, and at the same time can ensure that the called function will not inadvertently modify the value of other variables, increasing the reliability of the code.

In general, the use of  const keywords can help programmers find potential errors when writing programs, improve the robustness of the code, and increase the readability of the code.

demonstration:

Simulate implementation of library functions: strcpy

 General writing:

void my_strcpy(char* dest, char* src)
{
	while (*src != '\0')
	{
		*dest = *src;
		dest++;
		src++;
	}
	*dest = *src;//'\0'的拷贝
}

int main()
{
	char arr1[] = "hello world";
	char arr2[20] = "xxxxxxxxxxxxxxx";
	my_strcpy(arr2, arr1);
	printf("%s\n", arr2);
	return 0;
}

 The program works fine:

 But if we pass a null pointer in the function argument, the program will crash without any error message:

 After using assert:

 Although the program still crashes, this time there is an error message:

 Of course, the code can be simplified:

If you want the function to return the address of the destination string:

 Even so, the code is still not good enough, we can continue to strengthen the robustness of the code:

Because we only need to change the content pointed to by dest, but the content pointed to by src does not need to be changed. In order to prevent the content pointed to by src from being changed during the process of writing the program, we can add the keyword const before *src

 

In C language, const it can be used in the following aspects:

1. Define constants

Constants can be defined using  const keywords, and the value of the constant cannot be modified, for example:

2. Constant pointer

const Constant pointers can be defined by using  keywords, that is, the pointer itself cannot modify the address it points to , for example:

 

The above code defines a pointer  pwhose type is ,  const char *that is, the pointer itself cannot be modified, and the value in the pointed address cannot be modified.

3. Pointer to constant

The keyword can be used  const to define a pointer to a constant, that is, the value in the address pointed to by the pointer cannot be modified, for example:

 The above code defines a pointer  pwhose type is ,  char * constthat is, the address pointed to by the pointer itself cannot be modified, but the value stored in the address can be modified.

const int *p, int const *p (pointer variable pointing to a constant variable, can point to a constant variable, and can also point to a variable that is not declared as const, but at this time only the pointed address can be modified, the value cannot be modified, and the pointed to The value of that variable cannot be modified by modifying the address of the pointer variable itself . If a variable has been declared as a constant variable, it cannot be used to initialize other variables, and only the pointer of the constant variable can be used to point to it. Instead of using a general non-const type pointer variable to point to it.)

int * const p (constant pointer to variable, can only modify the value, cannot modify the pointed address )

Summary: In addition to pointing to constant variables, pointer variables pointing to constant variables can also point to variables that are not declared as const. At this time, the variable can be accessed through the pointer variable, but the value of the variable cannot be changed through the pointer variable. If it is not accessed through a pointer variable, the value of the variable can be changed.
Note: defining a pointer variable p pointing to a constant variable and making it point to c1 does not mean that c1 is also declared as a constant variable, but only in During accessing c1 with a pointer variable, c1 has the characteristics of a constant, and its value cannot be changed. In other cases, c1 is still an ordinary variable, and its value can be changed.

When const modifies the pointer:

        When const is placed on the left of *, the content pointed to by the pointer is restricted. The content pointed to by the pointer cannot be changed through the pointer variable, but the pointer variable itself can be changed.

        When const is placed on the right side of *, the pointer variable itself is restricted, and the pointer variable itself cannot be changed, but the content pointed to by the pointer can be changed through the pointer

In general, const keywords can be used to restrict the use of variables, pointers, function parameters, function return values, etc., thereby improving the readability, maintainability and security of the program. It is a very important keyword in C language .

Simulate the implementation of the strlen function

 

Guess you like

Origin blog.csdn.net/m0_73648729/article/details/130833338