Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why bool is not represented using float?

Tags:

c

types

boolean

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?

like image 809
Shri Avatar asked Sep 05 '25 08:09

Shri


2 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;
}
like image 188
K. Brafford Avatar answered Sep 08 '25 03:09

K. Brafford


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

like image 37
Bernd Elkemann Avatar answered Sep 08 '25 01:09

Bernd Elkemann