简体   繁体   中英

Why bool is not represented using float?

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, ie:

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).

C's _Bool / bool (and C++'s bool ) is supposed to be a very simple numerical type and behave as one and you cannot get any simpler than something like char or int .

int is a typical choice for performance or historical reasons.

Substituting float would limit it. You won't be able to shift a float with << and >> .

You sometimes want to be able to shift the result of the operators like && , || , == , != , > , < , >= , <= , ! , which is of type bool in C++ and _Bool / bool in disguise in C (implicitly converted into int ).

With many reasons mentioned by other answers (slow, historical, etc.) I want to add that typically floating point numbers have ' Accuracy ' problem ( Ref: Wikipedia ). Who wants all of these problems to make computer say the 'Truth' or 'Falsehood'? I hope you wouldn't want either. And it's pointless to choose something which is 'NOT ACCURATE' for being used as 'boolean' value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM