2011-01-29 44 views
3

對於我的編譯器測試,我需要在我的測試代碼中生成此警告「聲明無效」。我怎樣才能做到這一點?如何在c/C++代碼中生成編譯器警告「聲明無效」

使用VS cl.exe時編譯器

+1

確保你的警告級別設置得足夠高。 – 2011-01-29 06:11:59

+1

哪個編譯器? – 2011-01-29 06:14:24

+0

謝謝大家。您的評論有幫助。 – user393148 2011-01-29 06:27:14

回答

2
int main() 
{ 
    5; // Statement has no effect 
    return 0; 
} 

編輯1上VC++ 2010

#include <iostream> 
#pragma warning(default:4555) 

int main() 
{ 
    5; 
    getchar(); 
    return 0; 
} 

輸出嘗試:

warning C4555:main.cpp(6): expression has no effect; expected expression with side-effect

注:看來VC++ 2010有他們的名單上沒有C4705警告。 MSDN Compiler Warnings

6
so ross$ cat > noeff.c 
void f(void) { 
    1; 
} 
so ross$ cc -Wall -c noeff.c 
noeff.c: In function ‘f’: 
noeff.c:2: warning: statement with no effect 
so ross$ 
1

還有一個:

x == 0; 

我發現其中的一個部分代碼(別人寫的)最近 - 我把它固定在預定的「x = 0;」。

Mac OS X 10.6.6上的GCC 4.2.1。

cc -Wall -c x.c 
x.c: In function ‘f’: 
x.c:5: warning: statement with no effect 

代碼:

int f(int x) 
{ 
    x *= 3; 
    if (x % 2 == 0) 
     x == 0; 
    return x; 
} 

你得到與其他編譯器依賴於其他編譯器。

0

下面的C代碼生成與VS2008以下警告不惜一切默認的警告級別爲編譯器:

int main() 
{ 
    int a = 0; 
    1; // this doesn't seem to generate a warning 
    a + 1; 
    a == 0; 

    return 0; 
} 

C:\temp\test.c(5) : warning C4552: '+' : operator has no effect; expected operator with side-effect 
C:\temp\test.c(6) : warning C4553: '==' : operator has no effect; did you intend '='? 

在你的意見,你似乎實際上是集中於得到警告C4705(「語句沒有影響」)。 According to MSDN,似乎該警告僅記錄在VS6中。所以我認爲如果你想要那個特定的錯誤代碼,你需要挖掘VC++ 6.

相關問題