Reputation: 237
I read somewhere that using BOOL (typedef int) is better than using the standard c++ type bool because the size of BOOL is 4 bytes (i.e. a multiple of 4) and it saves alignment operations of variables into registers or something along those lines...
Is there any truth to this? I imagine that the compiler would pad the stack frames in order to keep alignments of multiple of 4s even if you use bool (1 byte)?
I'm by no means an expert on the underlying workings of alignments, registers, etc so I apologize in advance if I've got this completely wrong. I hope to be corrected. :)
Cheers!
Upvotes: 8
Views: 10901
Reputation: 470
There are three commonly accepted performance-driven practices in regards to booleans:
I've never heard about any performance gain from substituting a boolean with (unsigned?) integer however.
Upvotes: 0
Reputation: 39109
The only guaranteed size you can get in C++ is with char
, unsigned char
, and signed char
2), which are always exactly one byte and defined for every platform.0)1)
0) Though a byte does not have a defined size. sizeof(char)
is always 1 byte
, but might be 40 binary bits in fact
1) Yes, there is uint32_t
and friends, but no, their definition is optional for actual C++ implementations. Use them, but you may get compile time errors if they are not available (compile time errors are always good)
2) char
, unsigned char
, and signed char
are distinct types and it is not defined whether char
is signed
or not. Keep this in mind when overloading functions and writing templates.
Upvotes: 2
Reputation: 500953
First of all, sizeof(bool)
is not necessarily 1
. It is implementation-defined, giving the compiler writer freedom to choose a size that's suitable for the target platform.
Also, sizeof(int)
is not necessarily 4
.
There are multiple issues that could affect performance:
What -- if any -- difference that makes to a particular piece of code can only be established by profiling that piece of code.
Upvotes: 9