Visual Studio 2010 (C++): suppress C4706 warning temporarily

后端 未结 5 838
萌比男神i
萌比男神i 2021-02-13 17:33

When you compile the following C++ source file in Visual Studio 2010 with warning level /W4 enabled

#include   // for printf
#include 

        
相关标签:
5条回答
  • 2021-02-13 18:10

    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");
    }
    
    0 讨论(0)
  • 2021-02-13 18:10

    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.

    0 讨论(0)
  • 2021-02-13 18:15

    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");
    }
    
    0 讨论(0)
  • 2021-02-13 18:18

    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.

    0 讨论(0)
  • 2021-02-13 18:23

    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");
        }
    }
    
    0 讨论(0)
提交回复
热议问题