Use of bool / stdbool.h in kernel

David Schultz das at FreeBSD.ORG
Mon Dec 5 18:16:32 UTC 2011


On Sun, Dec 04, 2011, mdf at freebsd.org wrote:
> On Wed, Nov 30, 2011 at 5:49 PM, David Schultz <das at freebsd.org> wrote:
> > Unfortunately, the "new type" is mostly useless, aside from
> > improving readability.  Unlike modern languages, C doesn't
> > consider it a compile-time error to mix up bools and ints.
> 
> Partly true.  In addition to changing the semantics of the ++ and --
> operators, _Bool is usually implemented as an 8-bit type and so
> pointers-to-bool and pointers-to-int are not compatible.  Also, C (or
> at least gcc? I don't know my C99 standard the way I know C89) will
> apply default promotion and casting rules, so that e.g. an assignment
> like:
> 
> int a;
> bool b;
> 
> a = 2;
> b = a;
> printf("%d", b);
> 
> will print 1.

What I meant by "mostly useless" is that programs like the above
don't elicit a compile-time error.  Static checks to prevent the
conflation of boolean and numeric types (unless you explicitly ask
for it) would promote correctness.  That's the most important
benefit of a boolean type, but with C99 you don't get that.
Kernighan even conceded as much in a paper advocating C over
Pascal.

The C99 bool type is still good for something because it documents
what the programmer meant, but the semantics are bizarre.  For
instance, gcc allows the statement 'return 2' in a boolean
function, and the result is that the function returns 1.

And incidentally, the "modern languages" I mentioned that get it
right include ALGOL 60!


More information about the freebsd-arch mailing list