Reputation: 43
I've been playing with some functions that return BOOL. I know how to use them but whats the difference between BOOL and bool? I've also looked at some example code from directX and they use it as a int? Is there a advantage to using int, bool, or BOOL? My main question is Which should I be using?
Upvotes: 2
Views: 960
Reputation: 4421
Most compilers will make the size of a bool
1 byte, whereas the size of an int
is usually 4 bytes.
There is an obvious saving in space if you use bool
for tightly packed structures in this case.
Now, in theory, moving and int
around is faster than moving a byte (int
is usually the native machine word). So in the sense of microoptimizations for maximum speed, a BOOL
that equals an int
is better than a bool
that equal a byte.
Upvotes: 0
Reputation:
Is there a advantage to using int, bool, or BOOL?
One advantage of using bool
over BOOL
is that you can overload functions on bool
.
// header file
void f( int ); // ok
void f( BOOL); // ok, redeclares the same function
...
// source file
void f( int ) { /*...*/ } // ok
void f( BOOL) { /*...*/ } // error, redefinition
For more information about why it makes sense to use bool
over BOOL
read this gotw by Herb Sutter
Upvotes: 1
Reputation: 912
For the best type safety, in new code you should use bool for a boolean. If you interface with things like a BOOL, automatic type conversion will generally work for you, but otherwise you just treat BOOL as a legacy integer represented boolean.
Upvotes: 1
Reputation: 263667
BOOL
is a Windows-specific type name; it's a typedef
(an alias) for int
.
Historically, it was probably invented by Microsoft before the built-in bool
type was added to C++.
For any new code that doesn't have to talk to the Windows API, just use bool
.
Use BOOL
only for code that has to conform to the Windows API.
(If the Windows API were being written from scratch today, presumably it would use C++'s built-in bool
type rather than inventing its own. BOOL
is a relic of history.)
Upvotes: 5