How to quickly inspect and analyse code for bugs (C++)
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.
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)
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.
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.
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.
精彩评论