經(jīng)驗分享:C++編程中的四個調(diào)試小技巧
下面介紹C++編程的四個小技巧,供大家參考。
1.調(diào)試標記
適用預(yù)處理#define定義一個或多個調(diào)試標記,在代碼中把調(diào)試部分使用#ifdef 和#endif 進行管理。當程序最終調(diào)試完成后,只需要使用#undef標記,調(diào)試代碼就會消失。常用的調(diào)試標記為DEBUG, 語句序列:
#define DEBUG
#ifdef DEBUG
調(diào)試代碼
#endif
2.運行期間調(diào)試標記
在程序運行期間打開和關(guān)閉調(diào)試標記。通過設(shè)置一個調(diào)試bool標記可以實現(xiàn)。這對命令行運行的程序更為方便。
例如下面代碼
- #include<iostream>
- #include <string>
- using namespace std;
- bool debug =false;
- int main(int argc,char*argv[])
- {
- for(int i=0;i<argc;i++)
- if(string(argv[i])==“--debug=on“)
- debug = true;
- bool go=true;
- while(go)
- {
- if(debug)
- {
- 調(diào)試代碼
- }else {}
- }
- }
3.把變量和表達式轉(zhuǎn)換成字符串
可是使用字符串運算符來實現(xiàn)轉(zhuǎn)換輸出定義
- #define PR(x) cout<<#x”=”<<x<<'\n'
4.c語言的assert()
該宏在<assert>中,,當使用assert時候,給他個參數(shù),即一個判讀為真的表達式。預(yù)處理器產(chǎn)生測試該斷言的代碼,如果斷言不為真,則發(fā)出一個錯誤信息告訴斷言是什么以及它失敗一會,程序會終止。
- #include< assert>
- using namsapce std;
- int main()
- {
- int i=100;
- assert(i!=100); //Fails
- }
- 當調(diào)試完畢后在#include<assert>前加入#define NDEBUG即可消除紅產(chǎn)生的代碼
- }
希望本文對你有幫助,一起來看。






















