When you compile the following C++ source file in Visual Studio 2010 with warning level /W4 enabled
#include // for printf
#include
Instead of trying to hide your warning, fix the issue it's complaining about; your assignment has a value (the value on the left side of the assignment) that can be legally used in another expression.
You can fix this by explicitly testing the result of the assignment:
if ((result = strcmp(str0, str1)) != 0)
{
printf("Strings are different\n");
}
There is a simple construction !!
to cast a type to bool
. Like this:
if (!!(result = strcmp(str0, str1)))
However, in some cases direct comparison != 0
might be more clear to a reader.
There is another solution which avoids the warning: the comma operator.
The main advantage here will be that you don't need parentheses so it's a bit shorter than the !=0
solution when your variable name is short.
For example:
if (result = strcmp(str0, str1), result)
{
printf("Strings are different\n");
}
The sane solution is to rewrite the condition to
if( (result = strcmp(str0, str1)) != 0 )
which will inform any C compiler that you really want to assign, and is almost certain to generate the same object code.
In MSDN Libray: http://msdn.microsoft.com/en-us/library/2c8f766e(v=VS.100).aspx, There is the section as follows.
For warning numbers in the range 4700-4999, which are the ones associated with code generation, the state of the warning in effect when the compiler encounters the open curly brace of a function will be in effect for the rest of the function. Using the warning pragma in the function to change the state of a warning that has a number larger than 4699 will only take effect after the end of the function. The following example shows the correct placement of warning pragmas to disable a code-generation warning message, and then to restore it.
So '#pragma warning' only works for an each function/method.
Please see the following code for more detail.
#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");
}
}