-1

为什么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 );
    }
}

你会得到:

./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 

在哪里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" %*

有问题的行不是布尔值:

    if( ( 2 > inputLevelSize > COMPUTE_DEBUGGING_DEBUG_INPUT_SIZE )
        || ( 2 > builtInLevelSize > COMPUTE_DEBUGGING_DEBUG_INPUT_SIZE ) )

如何正确地做表达式 as 0 < x < 10

所说的内容与解释器有关。例子:

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

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

4

3 回答 3

8

诸如此类的情况并不像a > b > c您认为的那样起作用。实际上它们的工作方式类似(a > b) > c(因为>运算符从左到右工作),但结果a > b是布尔值,因此是警告。

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

if(a > b && b > c)
于 2017-03-02T10:33:49.777 回答
3

如果您像比较它一样0 < x < 10首先评估0 < x哪个是真或假,然后将其与 10 进行比较。您需要将表达式分开,如0 < x && x < 10.

于 2017-03-02T10:37:47.590 回答
2

编写范围检查表达式的正确方法是:

( 0 < x ) && ( x < 10 )

如所写,该行计算为((0 < x) < 10)

于 2017-03-02T10:37:29.000 回答