2012-11-23 40 views
1

我經常寫這樣的代碼:未使用VAR

int result = someMethod(arg1,arg2,...); 
assert(result==0) 

比方說,斷言()是這樣定義的東西:

#ifdef DEBUG 
#define assert(e) if(!e) printf("something's wrong"); 
#else 
#define assert(...) 
#endif 

的第一段代碼將給予警告'結果'是一個未使用的變種。

我可以這樣做:

#ifdef DEBUG 
    int result = someMethod(arg1,arg2,...); 
#else 
    someMethod(arg1,arg2,...); 
#endif 
assert(result==0) 

,但似乎相當不幹了......

還有什麼我能做什麼呢?

+0

你爲什麼重新定義'assert'?只是'#include '。另外請注意,通常使用'NDEBUG'而不是'DEBUG'。 –

+0

對不起,迂腐,但C沒有辦法。 SomeMethod()應​​該被命名爲someFunction()。 –

+0

@WilliamPursell你說得對,那很愚蠢:-) – Grav

回答

4
int result = someMethod(arg1,arg2,...); 
assert(result==0); 
(void)result; 
0

空格和換行是無關的編譯器,所以...

#ifdef DEBUG 
    int result = 
#endif 
    someMethod(arg1,arg2,...); 
assert(result==0) 
+0

你可能想把它包裝在一個宏中以使它可用。 – pmr

+0

@pmr只是顯示機制,但是...更好的一個宏。 – HostileFork

1

assertion_code宏來使某些代碼段只在調試配置。

#if defined(NDEBUG) 
#define assertion_code(v) 
#else 
#define assertion_code(v) v 
#endif 

現在你可以寫

assertion_code(int result =) expr(); 
assert(result == 0); 
0

有明確的方式:

static inline void debug(const char *msg) 
{ 
#ifdef DEBUG 
    printf("%s\n", msg); 
#else 
    (void)msg; 
#endif 
} 

然後:

if (someMethod(arg1,arg2,...) != 0) { 
    debug(message); 
} 

由於有一個公平的機會,你不會當有些事情是錯誤的時候,希望繼續正常進行無論如何,條件子句可能會很有用。或者當您打算關閉DEBUG時,您是否打算忽略錯誤?