当前位置:网站首页>Eight common errors in programming
Eight common errors in programming
2022-06-24 01:25:00 【CPP development frontier】
Everybody knows , Learning programming is a very boring thing , In particular, you can never get the desired results when running the program , After some debugging, it still cannot be solved , I believe every programmer has encountered this kind of situation , This is also a necessary stage for the birth of a great programmer .
Sadly , The same mistakes continue to happen . But luck followed , ad locum , I'll introduce the most common new programmers I've ever met 8 A collection of errors , Convenient for everyone to learn
1 Use sheet “=” Check for equality
char x='Y';
while(x='Y')
{
//...
cout<<" Whether or not to continue ? (Y/N)";
cin>>x;
}The above code will be an endless loop ~~ As free as the wind ~~~
The code uses an equal sign to check whether the loop condition is equal , In fact, the program will assign the value on the right side of the expression to the variable on the left during execution , In fact, the assignment of variables is performed . In this case , The value is 'Y', It is regarded as true. therefore , The cycle will never end . Therefore, the following changes are required to solve the above problems :
- Use == Check for equality ;
- To avoid accidental assignment , Put the variable to the right of the expression , If you accidentally use an equal sign , There will be compilation errors , Because you can't assign a value to something that isn't a variable .
char x='Y';
while('Y'==x)
{
//...
cout<<" Whether or not to continue ? (Y/N)";
cin>>x;
}2 Variable assignment
#include <iostream>
using namespace std;
int main()
{
int a, b;
int sum=a+b;
cout<<"input two numbers to add: ";
cin>>a;
cin>>b;
cout<<"The sum is: "<<sum;
return 0;
}After the above code is run, the result is as follows :
Give it to a and b It's all assigned , Why? sum Or will you get an outlier ? Let's see what happens in the program . Usually beginners think that variables act like equations —— If you assign a variable to the result of several other variables , When these variables change , As in the code a and b, The value of the variable (sum) It's going to change . But this is not the case . stay C++ in , Once you assign a value to a variable , The value of this variable will not change , Unless you assign him a new value . therefore , In the program above , Because at first I gave sum An uninitialized variable is used for assignment ,sum You will also get a random value , Although the back is right a and b It's assigned , however sum It won't be changed .
3 Variable not declared
#include <iostream>
using namespace std;
int main()
{
cin>>x;
cout<<x;
return 0;
}Compile time , The compiler will report an error . Because the compiler doesn't know that we x The meaning of , So it must be declared when using . as follows :
#include <iostream>
using namespace std;
int main()
{
int x=0;
cin>>x;
cout<<x;
return 0;
}4 Variable not initialized
#include <iostream>
using namespace std;
int main()
{
int count;
while(count<100)
{
cout<<count<<";";
count++;
}
return 0;
}The code above is executed , Not as expected while loop , Because in C++ in , Integer variables are not assigned by default 0. In the code above count It can be int Any value in the range . for example , It may be 121, under these circumstances ,while The condition of a loop is never true . The output of the program may be output from -99 To 99 The number of .
Bear in mind : Variables must be initialized !!!
5 Function undefined
int main()
{
add();
}
void add()
{
//...
}Error will be reported at compile time , It is clearly defined later add function , Why is there no definition add~
When compiling code , The compiler doesn't know add() What is the , Unless you tell it in advance , If you tell it that there is a name after using it add Function of , It will be confused . So be sure to use the function for the first time , Just define the prototype of the function or the entire definition of the function . Such as :
void add()
{
//...
}
int main()
{
add();
}6 Redundant semicolons
Most of these problems occur in for In circulation , Such as :
#include <iostream>
using namespace std;
int main()
{
int x;
for(x=0; x<100; x++);
cout<<x;
return 0;
}The above code is expected to output 0 To 99 The numerical , But after the actual operation, the output is :100; The reason is that for There is an extra semicolon after the statement . This will change the original logic of the code . So remember when programming : Semicolons cannot appear in if sentence 、 After loop or function definition . If you put one of these places , Your program will not work properly .
7 Array boundary overflow
#include <iostream>
using namespace std;
int main()
{
int array[10];
for(int i=1; i<=10; i++)
cout<<array[i];
return 0;
}stay C++ The array index is derived from 0 Start . for example , If you have one 10 Array of elements , The first element is at position 0, The last element is in position 9.
int array[10]; for(int =1; i<10; i++) cout<<array[i];
There are other problems in the above code , If the array is not initialized , So when outputting , The printed values are actually random values .
8 Misuse “&&” and “||”
#include <iostream>
using namespace std;
int main()
{
int value;
do
{
//...
value=10;
}while(!(value==10) || !(value==20));
return 0;
} The original intention of the code implementation should be to value be equal to 10 perhaps value be equal to 20 When , Just close the loop . However, it is found that , Even if value be equal to 10, The loop statement will also be executed all the time . from while Expression analysis shows that . It can't exist at the same time value Equal to 10 It's equal to 20 The situation of . If you want to meet the end condition of the above cycle , You need to change the expression to :!(value==10) && !(value==20) perhaps !((value==10) || (value==20)) To meet the exit conditions . If you have any questions about this condition, you can review discrete mathematics by yourself .
边栏推荐
- Pad User Guide
- How does the fixed assets management software reduce costs and increase efficiency for enterprises?
- CVPR2022 | 可精简域适应
- JS stack memory
- Use recursion to form a multi-level directory tree structure, with possibly the most detailed notes of the whole network.
- Isn't this another go bug?
- Dart series part: asynchronous programming in dart
- GNN upper edge distributor! Instead of trying to refine pills, you might as well give your GNN some tricks
- Zhongshanshan: engineers after being blasted will take off | ONEFLOW u
- 7 tips for preventing DDoS Attacks
猜你喜欢

Use recursion to form a multi-level directory tree structure, with possibly the most detailed notes of the whole network.

GNN upper edge distributor! Instead of trying to refine pills, you might as well give your GNN some tricks
![[machine learning] linear regression prediction](/img/74/9b5067bb9057049c998898ff2457f1.png)
[machine learning] linear regression prediction

LMS Virtual. Derivation method of lab acoustic simulation results

985 Android programmers won the oral offer of Alibaba P6 in 40 days. After the successful interview, they sorted out these interview ideas

JS input / output statements, variables

An accident caused by a MySQL misoperation, and the "high availability" cannot withstand it!

一次 MySQL 误操作导致的事故,「高可用」都顶不住了!

用一个软件纪念自己故去的母亲,这或许才是程序员最大的浪漫吧

LSF opens job idle information to view the CPU time/elapse time usage of the job
随机推荐
One article introduces you to the world of kubernetes
Application configuration management, basic principle analysis
Shengdun technology joined dragon lizard community to build a new open source ecosystem
jdbc
Salesforce batch apex batch processing (I)
How to learn website construction does website construction need code
【Flutter】如何使用Flutter包和插件
ShardingSphere-proxy-5.0.0容量范围分片的实现(五)
SAP executes PGI on the delivery order of STO and reports an error -fld selectn for Mvmt type 643 acct 400020 differences
Implementation of automatic triggering of inward delivery order after outward delivery order PGI in SAP inter company sto process
What is the website domain name trademark registration process? What is the use of a website domain name trademark?
[machine learning] linear regression prediction
CODING CD
What you don't know about traifik
13 `bs_duixiang.tag标签`得到一个tag对象
How to build high quality and high brand websites what should be paid attention to in the construction of enterprise websites
Shardingsphere-proxy-5.0.0 implementation of capacity range partition (V)
The best Base64 encoding and decoding tutorial in the whole network, with 6 examples!
Local cache selection (guava/caffeine/ohc) and performance comparison
How to build a high-quality website