Image

Imagedoctor_nemesis wrote in Imagecpp

Logical Comparisons

I just noticed in another post a comment about comparison statements such as this being confusing:
if( blVariable == true )

It's very bad to do something like that in C, and I didn't think it was much better in C++.

My reasoning is that whilst true and false in C++ might be guaranteed to be correct for the hardware the code is compiled for (TRUE and FALSE are not in C, but it's sort of complicated), it's very easy for boolean comparisons to cause strange errors.

Here is why.

Example pseudo-code:
void Function( bool blVariable )
{
   // Some code.

   if( blVariable == true )
   {
      // True circumstance code.
   }

   // Some more code.

   if( blVariable == false )
   {
      // False circumstance code.
   }
}

So in this function, the programmer assumes that either the true or false circumstance code will be executed, right? Well maybe not. If memory corruption occurs, then the value could be out of the range of a bool, leading to unpredictable behaviour in the function.

Does a C++ programme trap that the bool is out of range by default? On most platforms the range will be 0 or 1. Would it only be caught by runtime type checking? Or does the assembler of a boolean compare equal the C equivalent of something like:
if( ( blVariable & 1 ) == 1 )

Which would work at all times. My hunch is that it doesn't, but I wondered what other people thought...