Deeply understand the C language grammar traps of the C language series (the trap points that are often set in the exam questions, the types of errors and defects that must be avoided)

1. Assignment and equal
=: Assignment operation a=3;means assigning 3 to a variable.
==: Comparison operation, which a==3;means judging whether a is equal to 3, if it is equal, it returns 1, otherwise it returns 0.

2. Bitwise AND, Logical AND
&&: Logical AND is a logical operator, the rule is "two truths are true, and there is a false one."
&: Bitwise AND is a bitwise operator that converts two sets of data into binary, and performs AND operations in sequence after corresponding positions.
01
For details, please see the article: Practical Basics of C Language (Efficient and fast learning essence, more practical sentence cases) 11 o'clock bit operation.

3. Greedy method

  • The first point
a---b;等于a-- -b;  //先a-b,再a--
不等于a- --b;  //--b先做自减运算,再a-b

For example: a—b

	int a=3;
	int b=2;
	int c=a---b;
	printf("%d,%d,%d",a,b,c);

The result is:
if 2, 2, 1 is changed to a- --b, the result is 3, 1, 2

  • The other, because the "*" sign is a pointer sign, and the C language comment symbol is /*, the following traps may occur when referencing pointer data for operations:
y = x/*p;   //表示的是注释,p是注释中的内容
y = x / *p;  //这样表示的才是x除*p指针指向的数据
也可以写成:y = x / (*p);这样更加清晰一些

4. Numbers starting with 0
If the first digit of an integer constant is 0, the constant will be treated as an octal number, so 10 and 010 represent decimal 10 and 8, respectively.

5. Characters and strings

  • The character enclosed in single quotation marks represents the ASCII code value of the character;
  • The string enclosed in double quotes represents a pointer to the starting character of an unnamed array, which is initialized with the characters between the double quotes and an extra'\0' (string flag).
  • In the string enclosed by double quotation marks, the comment symbol /* is part of the string; the double quotation mark "" that appears in the comment is also part of the comment.
    Therefore, the statement: printf("The world")is equivalent to the following statement:
char str[]= {
    
    'T','h','e',' ','w', 'o','r','l','d','\n'};
printf(str);

6. End semicolon
A semicolon represents the end of a sentence.
therefore

if(x[i] > b);
	b = x[i];
if(x[i] > b){
    
    }
	b = x[i];
if(x[i] > b)
	b = x[i];

The first two sentences are equivalent, if and assignment statement are two independent statements; and the assignment statement in the third sentence is in if.

7. "Hanging" else
consider the following program fragments:

if(x == 0)
	if(y == 0)
		error();
else{
    
    
	z = x+y;
	f(5);
}

The else in this code appears to be parallel to the first if statement (x==0), but in fact the else will be prioritized and parallel to the nearest if statement.
Therefore, the else execution condition here is, y! = 0, not x! = 0.

  • So in this situation, I want to make the execution condition of else become y! = 0, then the above code can be modified to:
if(x == 0)
{
    
    
	if(y == 0)
		error();
}
else{
    
    
	z = x+y;
	f(5);
}

Here, the {{ brackets are used cleverly, and the second if statement (y0) is wrapped in the first if statement, so the else and if(x0) becomes a tie.

8. Non-array pointer

  • Suppose we want to concatenate two strings s and t to form a string r, we can use the library functions strcpy() and strcat():
char *r;
strcpy(r,s);
strcat(r,t);

This is actually impossible, because the address pointed to by r should also have memory space for the string, and this space should be allocated in some way.

  • So we allocate a certain amount of storage space to r this time:
char r[100];
strcpy(r,s);
strcat(r,t);

As you can see, we allocated a size of 100, but we cannot ensure that r is large enough to hold the string after the concatenation of s and t.

  • So we can use malloc() function to allocate memory:
char *r, *malloc();
r = malloc(strlen(s) + strlen(t));
strcpy(r,s);
strcat(r,t);

In this way, we manually develop a piece of memory for r, the size of which is the sum of the number of characters in s and t.

  • However, this is not good enough. The malloc() function may not be able to provide the requested memory. In this case, the malloc function will return a null pointer as an event signal of "memory allocation failure". The following is a more complete code:
char *r, *malloc();
r = malloc(strlen(s) + strlen(t) + 1);  //需要多分配一个内存空间,以装一个空字符作为字符串结束标志
if(!r)  // 判空语句
{
    
    
	complain();
	exit(1);
}
strcpy(r,s);
strcat(r,t);

free(r);  ///释放暂时申请的内存空间r

9. Array declaration of parameters

  • When passing parameters in a function, the C language will automatically convert the array as a parameter to a pointer declaration, that is to say:
int strlen(char s[]){
    
    		;		}

versus

int strlen(char *s){
    
    		;		}

Are equivalent.

  • But these two are not equivalent:
extern char *hello;
extern char hello[];
  • A pointer parameter represents an array:
main(int argc, char *argv[]){
    
    	;	}
main(int argc, char **argv){
    
    	;	}

The second parameter in the main function is that a pointer parameter represents an array.

10. Avoid the "symmetry method"
In the C language, it is easy to confuse the pointer and the data pointed to by the pointer, especially when dealing with strings.

char *p, *q;
p = "xyz";

The assignment in the second line is incorrect. The value of p is actually an address value and should not be a data value.

11. Null pointer is not a null string.
Null pointer refers to a pointer to NULL or 0. If a null pointer is defined, the pointer cannot point to the content stored in the memory, so output operations cannot be performed:

printf(p);
printf("%s",p);

Both of these outputs are illegal.

12. Asymmetric boundary
In C language, an array with 10 elements has a subscript ranging from 0 to 9. Then 0 is the first "bound-in point" of the array subscript (refers to the point within the range of the array subscript, including boundary points), and 10 is the first "out-of-bound point" in the array subscript (refers to Are points within the range of the array subscript, excluding boundary points).
Because of this, we can write:

int a[10], i;
for (i=0; i<10; i++)
	a[i] = 0;

Instead of writing:

itn a[10], i;
for(i=0; i<=9; i++)
	a[i] = 0;

13. Evaluation order
Evaluation order and operator precedence are two different concepts, for example:

a < b && c <d;

In this sentence, if a is greater than or equal to b, there is no need to judge c<d because the expression must be false.

14. Operators &&, || and!
In some cases, the logical operators &&, || and! are replaced with bitwise operators &, | and ~! , The program seems to work normally, but in fact this is just a coincidence.
In the C language, it is generally agreed to treat 0 as false, and non-zeros are all true.

15. Macro definition with parameters
In the C language macro definition, the passed parameters will not be automatically bracketed, which means that when passing parameters, it is just a simple replacement, and the priority of addition, subtraction, multiplication, and division will not be judged. For example:

#include <stdio.h>
#define A(a, b) a*b  //简单替换的宏定义
#define B(a, b) ((a)*(b))  //会判断的宏定义 
 
int main()
{
    
    
	printf("A=%d\bB=%d",A(3+7,5), B(3+7,5));	
}

The output results are:
02

The article is referenced in the literature: "C Traps and Defects" [America] Andrew Koening

Guess you like

Origin blog.csdn.net/Viewinfinitely/article/details/109741454