Nub*_*bok 12 visual-studio-2010 compiler-warnings suppress-warnings visual-studio visual-c++
在Visual Studio 2010中编译以下C++源文件时启用了警告级别/ W4
#include <cstdio> // for printf
#include <cstring> // for strcmp
char str0[] = "Hello";
char str1[] = "World";
int main()
{
int result;
if (result = strcmp(str0, str1)) // line 11
{
printf("Strings are different\n");
}
}
Run Code Online (Sandbox Code Playgroud)
你得到以下警告
警告C4706:条件表达式中的赋值
对于第11行.
我想在这个地方准确地压制这个警告.所以我尝试了Google并找到了这个页面:http://msdn.microsoft.com/en-us/library/2c8f766e(v = VS.100).aspx
所以我将代码更改为以下内容 - 希望这可以解决问题:
#include <cstdio> // for printf
#include <cstring> // for strcmp
char str0[] = "Hello";
char str1[] = "World";
int main()
{
int result;
#pragma warning(push)
#pragma warning(disable : 4706)
if (result = strcmp(str0, str1))
#pragma warning(pop)
{
printf("Strings are different\n");
}
}
Run Code Online (Sandbox Code Playgroud)
它没有帮助.
这个变体也没有帮助:
#include <cstdio> // for printf
#include <cstring> // for strcmp
char str0[] = "Hello";
char str1[] = "World";
int main()
{
int result;
#pragma warning(push)
#pragma warning(disable : 4706)
if (result = strcmp(str0, str1))
{
#pragma warning(pop)
printf("Strings are different\n");
}
}
Run Code Online (Sandbox Code Playgroud)
为了避免进一步的询问:我在每次编译之前清理了解决方案.所以这可能不是错.
总结一下:如何在这个地方完全抑制C4706?
编辑是的,重写是可能的 - 但我真的想知道为什么我试图压制警告的方式(在MSDN上正式记录)不起作用 - 哪里出错?
Rob*_*Rob 18
而不是试图隐藏你的警告,解决它抱怨的问题 ; 你的赋值有一个值(赋值左侧的值),可以在另一个表达式中合法使用.
您可以通过显式测试赋值结果来解决此问题:
if ((result = strcmp(str0, str1)) != 0)
{
printf("Strings are different\n");
}
Run Code Online (Sandbox Code Playgroud)
小智 14
在MSDN Libray中:http://msdn.microsoft.com/en-us/library/2c8f766e(v = VS.100).aspx,有以下部分.
对于4700-4999范围内的警告编号(与代码生成相关的编号),编译器遇到函数的开括号时生效的警告状态将对函数的其余部分生效.使用函数中的警告编译指示来更改数字大于4699的警告的状态仅在函数结束后生效.以下示例显示警告编译指示的正确放置,以禁用代码生成警告消息,然后还原它.
因此'#pragma warning'仅适用于每个函数/方法.
有关更多详细信息,请参阅以下代码.
#include <cstdio> // for printf
#include <cstring> // for strcmp
char str0[] = "Hello";
char str1[] = "World";
#pragma warning(push)
#pragma warning( disable : 4706 )
void func()
{
int result;
if (result = strcmp(str0, str1)) // No warning
{
printf("Strings are different\n");
}
#pragma warning(pop)
}
int main()
{
int result;
if (result = strcmp(str0, str1)) // 4706 Warning.
{
printf("Strings are different\n");
}
}
Run Code Online (Sandbox Code Playgroud)
理智的解决方案是将条件重写为
if( (result = strcmp(str0, str1)) != 0 )
Run Code Online (Sandbox Code Playgroud)
这将通知任何 C编译器您真正想要分配,并且几乎肯定会生成相同的目标代码.
还有另一种解决方案可以避免警告:逗号运算符。
这里的主要优点是不需要括号,因此!=0当变量名称很短时,它比解决方案要短一些。
例如:
if (result = strcmp(str0, str1), result)
{
printf("Strings are different\n");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9688 次 |
| 最近记录: |