关于调试的建议(英文的,翻译稍后就来)

本文为编程初学者提供了有效的调试技巧,强调不应盲目修改代码,而应通过使用调试工具定位问题源头,并逐步排除错误。介绍了几种实用的方法,如保留代码版本、逐行检查等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

for beginning programmers.

Don't try to fix a bug before you've found the bug.
I know it's tempting. You know that there is a programming errorsomewhere around these lines of code. Hmmm..., there's an i*j. Perhapsit was meant to be i/j. Let's change it and maybe that'll help. Ibelieve that this kind of thought process is nearly alwayscounterproductive. Instead you should be examing the code. Is i*j whatyou intended to write? If so, then leave it alone and search elsewherefor the error.

The counterproductivity comes from the fact that making a randomchange can sometimes hide the real error. The program is crashing withi+1, so you change it to i--and the crash stops! Is this a good thing?Not if the correct value for the code was i+1. In that case, you arejust hiding the real source of the error.

Debugging is all about gathering more information.
When a program is not working, you must use a debugger (or othermeans) to find the earliest point in the program where the state ofthe program differs from what you expect. As you step through aprogram, all the values are right and you expect that the else-branchof an if-else statement will be taken...but the program steps into theif-branch instead. Or everything is right and you expect that thevalue of i will be changed to 42, but it is changed to 24 instead.

Always concentrate on finding the earliest point in the execution ofthe program where the program's state differs from what you expected.

Another information-gathering technique is to start throwing thingsout of the program. Not permanently! (This technique should be done ona copy of your program, not on the original.) The goal in this case isto make a tiny program that still gives unexpected results. If youbring me a six-line program that is misbehaving, it will be easier forme to find the error than with a 600-line program.

Keep a running series of your code.
As you modify your code, save a copy periodically. There are somesystems that will do this for you automatically, so that you canrecover any earlier stage. But if you don't have such a system, thenmake your own series of program000.cxx, program001.cxx, program002.cxx...

Remove wrong code completely.
Once you know that a piece of code is wrong, remove it from yourworking copy completely. Do not take it out with a comment (take itout completely).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值