如何快速检查和分析代码中的错误 (C++)
假设您刚刚编写了一些大代码,它可以编译并且一切都很好......但最终,结果不是预期的或者代码只是崩溃了。代码中存在一些错误,您必须在所有(几乎)行中查找它...
一种方法是在每个循环/重要函数之后放置 cout/printf ,以便查看变量如何变化以及在哪里错误。这显然是有效的,并且使用它我发现了一些编码时常见的错误。但是,如果有很多变量和很多函数/循环 - 将 cout 放入每个变量中几乎是不可能的。必须有其他方法来做到这一点。
这就是为什么我在这里问 - 除了上面描述的愚蠢方法之外,还有什么方法可以跟踪代码中变量的值吗?我听说过调试,但不太确定它到底意味着什么以及它有什么作用。
Let suppose you've just written some big code, it compiles and everything's fine...But in the end, the result is not the expected or the code simply crashes. There's some bug in the code, and you have to look for it in ALL (nearly) the lines...
One way is to just put cout/printf after each loop/important function so to see how the variables are changing and where is the mistake. This apparently works, and using it i've discovered some of my usual mistakes while coding. But if there are a lot of variables and a lot of functions/loops - putting cout in each of them for every variable is nearly impossible. There must be some other way to do this.
That's why I am asking here - Is there any way to track the values of the variables in the code other than the silly method described above ? I've heard debugging but not really sure what exactly does it mean and what does it do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 调试器
大多数(如果不是全部)流行的 C++ 开发环境都有一个调试器。我认为如果没有它,你就无法开发不平凡的代码。
(是的,我知道 TDD 中有一项运动,规定如果您有足够的测试覆盖率,则不需要调试器。这是完整的@rse IMHO)
Use a Debugger
There's a debugger for most (if not all) popular C++ development environments. I'd be of the opinion that you cannot develop non-trivial code without one.
(Yes I'm aware there's a movement in TDD that states if you've sufficient test coverage you don't need a debugger. Which is complete @rse IMHO)
如果你能改进的话,这个方法很好。您应该做
,而不是测试一切
人们习惯于一分为二代码(分而治之),直到找到错误。
当然,您应该学习如何在编程环境中使用调试器。
That method is good if you can improve it. Instead of testing everything, you should make
it a habit to bisect the code (divide and conquer) until you locate the bug.
And of course you should learn how to use a debugger on your programing environment.
您使用什么来调试取决于您的环境。在 IDE 中,您通常会使用 IDE 的内置调试器,但如果您使用命令行, GDB 可能是一个不错的选择。
What you use to debug depends on your environment. In an IDE, you would usually use the IDE's builtin debugger, but if you're working at the commandline, GDB's probably a good choice.