Search code examples
c++visual-studio-2015cl

Why the `warning C4804: '>': unsafe use of type 'bool' in operation` is popping on Visual Studio 2015?


Why the warning C4804: '>': unsafe use of type 'bool' in operation is popping on Visual Studio 2015?

If you run this code:

#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 );
    }
}

You will get:

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

Where cl_env.bat is:

@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" %*

The lines in question are not bool:

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

How to correctly do expressions as 0 < x < 10?

What do was said is relative to the interpreter. Examples:

  1. When an C++ standard states the compiler must to understand 0 < x < 10 as ( 0 < x ) && ( x < 10 ), but the compiler is actually is understanding it as ( 0 < x ) < 10, we call it a compilers bug.

  2. Therefore when the user states the compiler must to understand 0 < x < 10 as ( 0 < x ) && ( x < 10 ), but compiler is actually understanding it as ( 0 < x ) < 10, we call it a user's bug.


Solution

  • Conditions like a > b > c do not work the way you think they do. In fact they work like (a > b) > c (since the > operator works left-to-right), but the result of a > b is a boolean, thus the warning.

    The correct way would be to use && (logical and):

    if(a > b && b > c)