Re: bool implementation

From: Doug Harrison [MVP] (dsh_at_mvps.org)
Date: 01/15/05


Date: Sat, 15 Jan 2005 07:00:14 -0600

Mark Randall wrote:

>Might as well use char or unsigned char, both evaluate likewise to true,

There are big differences between those types and bool. Conversion from
non-bool to bool essentially goes like this:

 // x is bool, y is non-bool integral type or pointer
 x = y != 0; // What you really get when you say x = y;

Besides working for pointers, bool does the right thing for wider types. For
example:

unsigned x = 0x100;
unsigned char y = x;
bool z = x;

Now, x is considered "true" for all values != 0. Assuming VC's data types, y
is false for all values of x >= 0x100. However, z is true whenever x is
"true".

>small performance hit tho.

Using a bool can indeed result in a small performance hit when assigning
values of types other than bool to it, due to the conversion performed.

-- 
Doug Harrison
Microsoft MVP - Visual C++


Relevant Pages

  • Re: I Need an IsNumeric Method
    ... public bool IsNumeric ... //Try a double conversion. ... try to convert and catch the exception ... > o Don't forget that .5 is generally considered okay, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Testing for nullptr for a ref object
    ... I'm must admit I haven't read much of the C++/CLI standard. ... my interpretation is that the compiler will consider a conversion ... from x to bool better than the check against nullptr. ... So if a conversion from x to bool exists it will be chosen over the ...
    (microsoft.public.dotnet.languages.vc)
  • Re: void * instead of bool
    ... Earth would I definitily not want that to compile? ... One is that perhaps the original design dates from a time before 'bool' ... ifstream object to a constructor where one overload takes a bool. ... the latter case the conversion to ...
    (comp.lang.cpp)
  • Re: void * instead of bool
    ... If you have a conversion to bool then the following nonsense would compile ... Conversion to void* is less likely to be called accidentally. ... > (performance warning) ...
    (comp.lang.cpp)
  • Re: "a < b < c" not the same as "(a < b) && (b < c)"?
    ... >> The type _Bool is an integer type that can hold only two ... >> (Same for conversion.) No other integer type behaves ... An unsigned int bitfield of length one always holds either ...
    (comp.lang.c)