In C (before C99), booleans are usually represented as
typedef int bool;
#define true 1
#define false 0
Why it is represented as 'int' rather than 'float'?
This is an interview question, even I wonder why such question is asked! Any convincing answers?
bool
values are mostly used in comparisons, and using the int
type uses the integer ALU for these comparisons. It is very fast, as it's in the CPU's normal pipeline. If you were to use the float
type, then it would have to use the floating-point unit, which would take more cycles.
Also, if you wanted to support using your bool
type in mathematical expressions, i.e.:
x = (4 * !!bool1) + (2 * !bool1);
so as to avoid unnecessary branching, your use of the integer ALU would also be faster than using the floating point unit.
The above code is equivalent to the following branching code:
if (bool1) {
x = 4;
} else {
x = 2;
}
There are many many reasons why this would be a bad idea. But the reason why it was not done, ie the historical reason why it was not done that way is, that early computers did not have a floating point unit (and for an even longer period of time some had one and some did not).
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