適用預處理#define定義一個或多個調試標記,在代碼中把調試部分使用#ifdef和#endif進行管理。當程序最終調試完成后,只需要使用#undef標記,調試代碼就會消失。常用的調試標記為debug, 語句序列:
#define debug
#ifdef debug
調試代碼
#endif2、運行期間調試標記
在程序運行期間打開和關閉調試標記。通過設置一個調試bool標記可以實現。這對命令行運行的程序更為方便。例如下面代碼:
#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)
{
調試代碼
}else {}
}
}
3、把變量和表達式轉換成字符串
可是使用字符串運算符來實現轉換輸出定義
#define pr(x) cout<<#x”=”<<x<<'/n'
4、c語言的assert()
該宏在中,當使用assert時候,給他個參數,即一個判讀為真的表達式。預處理器產生測試該斷言的代碼,如果斷言不為真,則發出一個錯誤信息告訴斷言是什么以及它失敗一會,程序會終止。
當調試完畢后在#include<assert>前
#include< assert>
using namsapce std;
int main()
{
int i=100;
assert(i!=100);
//fails
}
加入#define ndebug即可消除紅產生的代碼
}
新聞熱點
疑難解答