Debugging Tips (2)

insert image description here
6. How to write good (easy to debug) code
6.1 Excellent code:

  1. the code works fine
  2. few bugs
  3. efficient
  4. high readability
  5. High maintainability
  6. Note clearly
  7. complete documentation

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.

Let’s talk about the role of assert and const here.
assert is equivalent to assert, and it is a good thing for a violent solution. If the things in the assert brackets do not meet the conditions, he will report an error, which is a good way to prevent some errors from happening. , of course we must include his header file <assert.h> when using it. When
const
const modifies pointer variables:

  1. If const is placed on the left of *, it modifies the content pointed to by the pointer, ensuring that the content pointed to by the pointer cannot be changed through the pointer
    . But the content of the pointer variable itself is mutable.
  2. If const is placed on the right side of *, it modifies the pointer variable itself, which ensures that the content of the pointer variable cannot be modified, but
    the content pointed to by the pointer can be changed through the pointer.

A simple summary is left fixed value, right orientation.

Let's talk about an example to let us see how to write good code
to simulate the implementation of the strcpy function

#include<string.h>
#include<stdio.h>
#include<assert.h>
char* my_strcpy(char* dest, const char* src)
{
    
    
	assert(dest && src);
	char* ret = dest;
	assert(dest && src);
	while (*dest++ = *src++)
	{
    
    
		;
	}
	return ret;
}
int main()
{
    
    
	char arr[] = "xxxxxxxxxxx";
	char arr2[] = "abcd";
	char* ret = my_strcpy(arr, arr2);
	printf("%s", ret);
	return 0;
}

7. Common errors in programming
7.1 Compilation errors
Directly read the error message (double-click) to solve the problem. Or it can be done with experience. Relatively simple.
7.2 Linked errors
Look at the error message, mainly find the identifier in the error message in the code, and then locate the problem. Typically the identifier name does not
exist or is misspelled.
7.3 Runtime errors
Use debugging to locate problems step by step.

That’s all for today’s sharing, thank you all! ! ! !

Guess you like

Origin blog.csdn.net/2301_76895050/article/details/132124255