The biggest features of the language are: powerful functions, convenient and flexible to use. The syntax check of C compiled programs is not as strict as other high-level languages, which leaves programmers with "flexibility". However, this flexibility brings a lot of inconvenience to program debugging, especially for beginners of C language, who often make mistakes that they don't even know where they are wrong. Looking at the wrong program, I don't know how to fix it. Through my study of C, I have accumulated some common mistakes in C programming, and I write them for your reference.
1. When writing identifiers, the distinction between uppercase and lowercase letters is ignored.
main()
{
int a=5;
printf("%d",A);
}
The compiler considers a and A to be two different variable names and displays an error message. C considers uppercase letters and lowercase letters to be two different characters. Conventionally, symbolic constant names are written in uppercase and variable names are written in lowercase to increase readability.
2. The type of the variable was ignored and illegal operations were performed.
main()
{
float a,b;
printf("%d",a%b);
}
% is the remainder operation, which gives the integer remainder of a/b. Integer variables a and b can be used for remainder operations, but real variables are not allowed to be used for remainder operations.
3. Confusing character constants with string constants.
char c;
c="a";
Here, character constants and string constants are confused. A character constant is a single character enclosed in a pair of single quotes, while a string constant is a sequence of characters enclosed in a pair of double quotes. C stipulates that "" is used as the end mark of a string, which is automatically added by the system. Therefore, the string "a" actually contains two characters: 'a' and '', and it is not possible to assign it to a character variable.
4. Ignoring the difference between “=” and “==”.
In many high-level languages, the "=" symbol is used as the relational operator "equals". For example, in a BASIC program you can write
if (a=3) then …
But in C language, "=" is the assignment operator and "==" is the relational operator. For example:
if (a==3) a=b;
The former is to compare whether a is equal to 3, and the latter means that if a is equal to 3, assign the value of b to a. Due to habit, beginners often make such mistakes.
5. Forgetting to add a semicolon.
The semicolon is an indispensable part of C statements and must be at the end of the statement.
a=1
b=2
When compiling, the compiler does not find a semicolon after "a=1", so it treats the next line "b=2" as part of the previous line, which will cause a syntax error. When correcting errors, sometimes no error is found in the line where the error is pointed out, so you need to check whether the semicolon is missing in the previous line.
{ z=x+y;
t=z/100;
printf("%f",t);
}
For compound statements, the final semicolon in the last statement cannot be omitted (this is different from PASCAL).
6. Add more semicolons.
For a compound statement such as:
{ z=x+y;
t=z/100;
printf("%f",t);
};
A semicolon should not be added after the curly braces of a compound statement, otherwise it would be superfluous.
Another example:
if (a%3==0);
I++;
Originally, if 3 divides a, I will increase by 1. However, since a semicolon is added after if (a%3==0), the if statement ends here, and the program will execute the I++ statement. Regardless of whether 3 divides a, I will automatically increase by 1.
Another example:
for (I=0;I<5;I++);
{scanf("%d",&x);
printf("%d",x);}
The original intention is to input 5 numbers in succession and output each number after inputting it. Because a semicolon is added after for(), the loop body becomes an empty statement. At this time, only one number can be input and output.
7. Forget to add the address operator “&” when entering a variable.
int a,b;
scanf("%d%d",a,b);
This is illegal. The Scanf function is used to store the values of a and b according to the addresses of a and b in memory. "&a" refers to the address of a in memory.
8. The way of inputting data does not meet the requirements. ①scanf("%d%d",&a,&b);
When inputting, you cannot use commas as separators between two data. The following input is illegal:
3, 4
When entering data, use one or more spaces between two data. You can also use the Enter key or the Tab key.
②scanf("%d,%d",&a,&b);
C stipulates that if there are other characters in the "format control" string besides the format description, the same characters as these should be entered when entering data. The following input is legal:
3, 4
It is incorrect to use spaces or other characters instead of commas at this time.
3 4 3:4
Another example:
scanf("a=%d,b=%d",&a,&b);
The input should be in the following form:
a=3,b=4
9. The format of the input characters does not match the requirements.
When you enter characters in the "%c" format, both "space characters" and "escape characters" are entered as valid characters.
scanf("%c%c%c",&c1,&c2,&c3);
For example, input abc
The character "a" is sent to c1, the character " " is sent to c2, and the character "b" is sent to c3. Because %c only requires one character to be read in, there is no need to use a space as the separator between two characters.
10. The data type of input and output is inconsistent with the format specifier used.
For example, a is defined as an integer, and b is defined as a real type. a=3; b=4.5;
printf("%f%dn",a,b);
No error message will be given during compilation, but the running result will not match the original intention. This kind of error needs special attention.
11. When entering data, attempt to specify precision.
scanf("%7.2f",&a);
This is illegal; you cannot specify precision when entering data.
12. The break statement is omitted in the switch statement.
For example: Print out percentage ranges according to the test score level.
switch(grade)
{ case 'A':printf("85~100n");
case 'B':printf("70~84n");
case 'C':printf("60~69n");
case 'D':printf("<60n");
default:printf("errorn");
Because the break statement is omitted, case only serves as a label, not a judgment. Therefore, when the grade value is A, the printf function executes the second, third, fourth, and fifth printf function statements after executing the first statement. The correct way to write it is to add "break;" after each branch. For example
case 'A':printf("85~100n");break;
13. Ignoring the detailed differences between while and do-while statements.
(1)main()
{int a=0,I;
scanf("%d",&I);
while(I<=10)
{a=a+I;
I++;
}
printf("%d",a);
}
(2)main()
{int a=0,I;
scanf("%d",&I);
do
{a=a+I;
I++;
}while(I<=10);
printf("%d",a);
}
As you can see, when the value of input I is less than or equal to 10, the two get the same result. When I>10, the two get different results. This is because the while loop first judges and then executes, while the do-while loop first executes and then judges. For numbers greater than 10, the while loop does not execute the loop body once, while the do-while statement executes the loop body once.
14. Misusing variables when defining arrays.
int n;
scanf("%d",&n);
int a[n];
The constant expression enclosed in square brackets after the array name can include constants and symbolic constants. That is, C does not allow the size of the array to be defined dynamically.
15. When defining an array, the "number of elements" defined is mistakenly taken as the maximum subscript value that can be used.
main()
{STatic int a[10]={1,2,3,4,5,6,7,8,9,10};
printf("%d",a[10]);
}
C language stipulates: a[10] is used in the definition, indicating that array a has 10 elements. Its subscript value starts from 0, so the array element a[10] does not exist.
16. Static storage is not used when initializing an array.
int a[3]={0,1,2};
It is wrong to initialize the array in this way. C language stipulates that only static storage arrays and external storage arrays can be initialized. It should be changed to:
static int a[3]={0,1,2};
17. The address operator & is added where it should not be added.
scanf("%s",&str);
The C language compiler system handles array names as follows: the array name represents the starting address of the array, and the input item in the scanf function is the character array name, so it is unnecessary to add the address symbol &. It should be changed to:
scanf("%s",str);
18. The formal parameters and local variables in the function are defined at the same time.
int max(x,y)
int x,y,z;
{z=x>y?x:y;
return(z);
}
Formal parameters should be defined outside the function body, while local variables should be defined inside the function body. It should be changed to:
int max(x,y)
int x,y;
{int z;
z=x>y?x:y;
return(z);
}
Previous article:Ping Programming in C
Next article:115.2K Serial Communication C Language Example
- Popular Resources
- Popular amplifiers
Professor at Beihang University, dedicated to promoting microcontrollers and embedded systems for over 20 years.
- Innolux's intelligent steer-by-wire solution makes cars smarter and safer
- 8051 MCU - Parity Check
- How to efficiently balance the sensitivity of tactile sensing interfaces
- What should I do if the servo motor shakes? What causes the servo motor to shake quickly?
- 【Brushless Motor】Analysis of three-phase BLDC motor and sharing of two popular development boards
- Midea Industrial Technology's subsidiaries Clou Electronics and Hekang New Energy jointly appeared at the Munich Battery Energy Storage Exhibition and Solar Energy Exhibition
- Guoxin Sichen | Application of ferroelectric memory PB85RS2MC in power battery management, with a capacity of 2M
- Analysis of common faults of frequency converter
- In a head-on competition with Qualcomm, what kind of cockpit products has Intel come up with?
- Dalian Rongke's all-vanadium liquid flow battery energy storage equipment industrialization project has entered the sprint stage before production
- Allegro MicroSystems Introduces Advanced Magnetic and Inductive Position Sensing Solutions at Electronica 2024
- Car key in the left hand, liveness detection radar in the right hand, UWB is imperative for cars!
- After a decade of rapid development, domestic CIS has entered the market
- Aegis Dagger Battery + Thor EM-i Super Hybrid, Geely New Energy has thrown out two "king bombs"
- A brief discussion on functional safety - fault, error, and failure
- In the smart car 2.0 cycle, these core industry chains are facing major opportunities!
- The United States and Japan are developing new batteries. CATL faces challenges? How should China's new energy battery industry respond?
- Murata launches high-precision 6-axis inertial sensor for automobiles
- Ford patents pre-charge alarm to help save costs and respond to emergencies
- New real-time microcontroller system from Texas Instruments enables smarter processing in automotive and industrial applications
- Timer capture
- Demystifying Medical Alarm Design, Part 1: IEC60601-1-8 Standard Requirements
- Answer questions to win prizes | Shijian Exploration: Water quality testing protects human safety
- Power amplifier circuit diagram design
- What factors need to be considered in the practical application of RFID?
- [AT-START-F403A Review] Part 6: On-chip Flash performance test
- Why can't the microcontroller receive data during Proteus simulation? The digital tube does not change
- nRF51802/nRF51822/nRF52832 Core Comparison
- [2022 Digi-Key Innovation Design Competition] + K210 & STM32F429-DK
- Regarding the problem of op amp, ask online