c/c++ 调试技巧小结

来源:互联网 发布:淘宝hd版下载 编辑:程序博客网 时间:2024/06/13 03:58

在c/c++中没有像c#/java那样强大的异常机制, 程序出了问题怎么办呢? 作为一个程序员呢,感觉是一小半的时间是在写代码,而一大部分的时间却一头扎在代码的雾水中,不断的debug, 辛苦呀, 今天我总结一下一些简单的调试技巧吧


技巧一:输出调试, 这个不用说了吧,也算不上技巧, 就是将想知道的数据直接输出来, 优点是灵活有针对性,但是太麻烦了


技巧二:调试标记法, 这个方法解决了不断输出中间结果的问题,分两种:

2.1. 预处理器调试标记:就是通过#define 定义一个或者是多个调试标记(在头文件中更合适),然后再需要调试的地方用#ifdef ???检测???的标记, 当调试完毕后就可以用#endif结束调试代码

实例代码如下:

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>#include <cassert>#include <cstdlib>#include <cassert>#define DEBUGusing namespace std;void test(){#ifdef DEBUGcout << "debug is power" << endl;#endif}int main(){test();return 0;}

2.2运行期间调试标记

然后另一种调试标记的方法是运行期间调试标记, 顾名思义就是在运行期间自己决定是否需要调试, 这种方法更加方便, 可以定义一个bool值来决定是否调试

下面是实例代码:

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>#include <cassert>#include <cstdlib>#include <cassert>#define DEBUG#define PR(x) cout << "x : " << (x) << endl;using namespace std;bool debug;void test(){int a = 10;if(debug){cout << " debug is power" << endl;PR(a);}}void Debug(){int dd;cout << "是否启动调试 1/0 :";cin >> dd;assert(dd == 1 || dd == 0);if(dd)debug = true;elsedebug = false;}int main(){#ifdef DEBUG     //预处理器调试标记Debug();     //运行期间调试标记#endiftest();return 0;}


技巧三:把变量和表达式转换成字符串的形式

在c/c++中的 # 是一个非常强大的符号, 如果能够用好, 对自己的代码调试有很大的作用, 下面看代码吧

实例如下:

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>#include <cassert>#include <cstdlib>#include <cassert>using namespace std;#define PR(x) cout << #x << " : " << (x) << endl;  // 和上面的那个PR(x) 看看有什么不同的效果吧int main(){int a = 123;PR(a);return 0;}

技巧四:利用c语言的assert()宏, 感觉这个在acm中式比较实用的,很是方便

assert()宏需要引用#include <cassert> 或者是#include <assert.h>, 这个宏会自动根据表达式生成调试代码,如果出错就会自动终止程序

实例如下:

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>#include <cassert>#include <cstdlib>#include <cassert>using namespace std;#define PR(x) cout << #x << " : " << (x) << endl;int mod(const int u, const int v){assert(v > 0);return u % v;        // 不能除零错误, 取模内部实现也是除法}int main(){int a = 123, b = 0, c = 10;PR(mod(a, b));PR(mod(a, c));return 0;}

还有很多我不知道的调试技巧希望可以大家共享呀

原创粉丝点击