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!
Surprisingly, g(bool) generates more asm instructions! Does it mean that if(bool) is little slower than if(int) ? I used to think bool is especially designed to be used in conditional statement such as if , so I was expecting g(bool) to generate less asm instructions, thereby making g(bool) more efficient and fast.
So do indeed use stdbool. h if you aren't bound to some existing home-brewed bool . It will be the standard type, with all the benefits that type brings in. Answer which actually gives the true reason: backward compatibility with already written code.
Treating integers as boolean values C++ does not really have a boolean type; bool is the same as int. Whenever an integer value is tested to see whether it is true of false, 0 is considered to be false and all other integers are considered be true.
It is something C programmer use, but C++ programmers should avoid, since C++ has bool . bool is a language integral type whose supported values are just true and false . When converted to int true becomes 1 and false becomes 0.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With