为什么`警告C4804:'>':在操作中不安全地使用类型'bool'在Visual Studio 2015上弹出?

use*_*ser -1 c++ cl visual-studio-2015

为什么warning C4804: '>': unsafe use of type 'bool' in operation在Visual Studio 2015上弹出?

如果您运行此代码:

#include <iostream>
#include <cstdlib>

int main( int argumentsCount, char* argumentsStringList[] )
{
#define COMPUTE_DEBUGGING_LEVEL_DEBUG      0
#define COMPUTE_DEBUGGING_DEBUG_INPUT_SIZE 32

    int inputLevelSize;
    int builtInLevelSize;

    inputLevelSize   = strlen( "a1" );
    builtInLevelSize = strlen( "a1 a2" );

    if( ( 2 > inputLevelSize > COMPUTE_DEBUGGING_DEBUG_INPUT_SIZE )
        || ( 2 > builtInLevelSize > COMPUTE_DEBUGGING_DEBUG_INPUT_SIZE ) )
    {
        std::cout << "ERROR while processing the DEBUG LEVEL: " << "a1" << std::endl;
        exit( EXIT_FAILURE );
    }
}
Run Code Online (Sandbox Code Playgroud)

你会得到:

./cl_env.bat /I. /EHsc /Femain.exe main.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

main.cpp
main.cpp(52): warning C4804: '>': unsafe use of type 'bool' in operation
main.cpp(53): warning C4804: '>': unsafe use of type 'bool' in operation
Microsoft (R) Incremental Linker Version 14.00.23506.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:main.exe 
main.obj 
Run Code Online (Sandbox Code Playgroud)

在哪里cl_env.bat:

@echo off

:: Path to your Visual Studio folder.
::
:: Examples:
::     C:\Program Files\Microsoft Visual Studio 9.0
::     F:\VisualStudio2015
set VISUAL_STUDIO_FOLDER=F:\VisualStudio2015

:: Load compilation environment
call "%VISUAL_STUDIO_FOLDER%\VC\vcvarsall.bat"

:: Invoke compiler with any options passed to this batch file
"%VISUAL_STUDIO_FOLDER%\VC\bin\cl.exe" %*
Run Code Online (Sandbox Code Playgroud)

有问题的行不是bool:

    if( ( 2 > inputLevelSize > COMPUTE_DEBUGGING_DEBUG_INPUT_SIZE )
        || ( 2 > builtInLevelSize > COMPUTE_DEBUGGING_DEBUG_INPUT_SIZE ) )
Run Code Online (Sandbox Code Playgroud)

如何正确表达式0 < x < 10

所说的是与翻译相关的.例子:

  1. 当C++标准声明编译器必须理解0 < x < 10( 0 < x ) && ( x < 10 ),但编译器实际上是理解它时( 0 < x ) < 10,我们将其称为编译器错误.

  2. 因此,当用户声明编译器必须理解0 < x < 10( 0 < x ) && ( x < 10 ),但编译器实际上将其理解为( 0 < x ) < 10,我们将其称为用户的错误.

Sin*_*all 6

条件不像a > b > c你认为的那样工作.实际上它们的工作方式(a > b) > c(因为>操作符从左到右),但结果a > b是布尔值,因此是警告.

正确的方法是使用&&(逻辑and):

if(a > b && b > c)
Run Code Online (Sandbox Code Playgroud)