« Why young women shouldn't own cars | Main | In a new light »

Bool-yah!

Warning: this is a nerdy entry. So you might want to come back some other time, if you don't dig this stuff... =)

Working as a professional programmer, you realize that there's just so much practical stuff you learn on the job that's never taught in the classroom, even at a top CS school like Stanford, that's nevertheless pretty important to know if you want to be the best at what you do. Today at work was one of those moments of learning.

Anyhow, most people know that in C++, there is a built-in bool type for boolean values. The exact implementation of this bool type is left to the compiler writer, though. Now, in Visual C++ and versions of gcc later than 3.0, bool is a byte that can only be TRUE or FALSE. In Visual C++, there's another type, BOOL (defined as a 32-bit int in the Windows header files) which can be NONZERO (TRUE) or ZERO (FALSE).

What's the difference, you may think. Well, the compiler sometimes generates extra code for a bool.

For example

return A != 0
for a bool must generate (in assembler)

if(A != 0)
  return 1;
else
  return 0;
In fact, Visual C will give you a “performance warning” error in this case.

While the same code for a BOOL can be

return A;

Similarly, the code bool

 A = (J != 4);
will generate a warning error and the code

if(J != 4)
  A = 1;
else
  A = 0;
The code
BOOL A = (J != 4);
will generate
A = !(J-4);

Now, if you're working with a deeply-pipelined processor, a branch misprediction can be costly in terms of cycles, so you can see why you want to avoid as much as possible, branching ops in your generated assembly code, especially in speed-critical inner loops. A BOOL being a 32-bit type rather than an 8-bit type is also more efficient for operations but less efficient for storage.

Now, of course, almost everything in CS can be thought of as a size vs. speed tradeoff: if you need to store arrays of bools (if you are, you aren’t coding well, though) an array of bool is better than an array of BOOL, but, if you really want to save space, you can use an array of bits, which take even longer than bools for operations but is far more efficient for storage.

Anyhow, I think I've bored everyone except for about 2 or 3, but this was fascinating to me. So people, check those typedefs! =)

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

About

This page contains a single entry from the blog posted on March 1, 2004 1:51 PM.

The previous post in this blog was Why young women shouldn't own cars.

The next post in this blog is In a new light.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.32