Does a equal to b? Even the program might return that they are the same, are they actually equal in all aspects in low level?
It all depends on what you mean by equal. The type is different, and that means that the representation in memory will probably differ (the compiler is free to represent those two as exactly the same, but it is also free to do otherwise). In most compilers/architectures, bool
takes just one byte of storage and int
has a bigger size (usually 4 bytes, but this depends on the architecture).
Besides the different sizes, the compiler will treat both types differently (not just the loads and stores to memory, but also the operations will be different. You can only store 0 and 1 in a bool, and that means that some operations might use that knowledge. For example, in this article you will find one case where the implementation of the test of a condition differs (note, the article has a case of undefined behavior that causes a bool
to evaluate to both true
and false
as for the test the compiler is assuming that the bool
can only be either 0 or 1, that cannot happen with int
)
From a logic point of view, the language determines how the different types are used in operations, and in particular if you try to compare a
and b
in your program, the result of the expression will be true
. Note that it does not mean that they are exactly the same, the language defines a set of conversion rules that are used to transform both variables into the same type and the comparison is performed in that type. In this case the conversion will be to int
. The bool
variable will be converted to 0
if false
or to 1
if true
.
Also, if I use code (pseudo) such as: if (a) execute()
, will execute() run?
Yes. In this case, the condition inside the if
requires a bool
value, so the conversion will be from int
to bool
. The standard defines that conversion to yield false
if the integer value is 0
, or true
otherwise, effectively doing the equivalent of if (a!=0)
. Since a
is 1
, the condition holds and execute()
will be evaluated.