bool different in C and C++?
Linus Torvalds
torvalds at linux-foundation.org
Sat Nov 18 10:11:53 PST 2017
On Sat, Nov 18, 2017 at 9:26 AM, Berthold Stoeger
<bstoeger at mail.tuwien.ac.at> wrote:
>
> Sure, but can these definitions be different for C and C++ on any sane
> platform?
Historically, yes, very much.
"bool" didn't really exist in C, so you will find code that does
#define int bool
or
typedef int bool;
all over the place
And yes, sometimes they use "char" too, but even then it's often
dangerous to use "bool" in C, because there's a big difference in
casting behaviour between a typedef and a "real" boolean type.
For example, if you do
bool var = flags & BITMASK;
then if it's a "native" bool it does the expected thing. If it's an
old-style C "typedef bool", it may not work at all, because the
casting from the (int) expression to the bool type is a bitwise cast,
rather than a "set to 0/1".
I think subsurface depends on new enough tools that this is never an
issue any more.
But in _general_ you should never use "bool" in C at all if you want
to be portable, because it's such a completely unreliable mess, and
can mean so many different things.
In fact, even when you can depend on a modern compiler, it's usually
best to restrict "bool" use entirely to just function return values
and very local use. In structure and union definitions, you're better
off using
unsigned int bit:1;
which has well-defined packing behavior and works well even if you mix
it with other non-bool bitfields (although the bit _ordering_ is still
entirely undefined, so if you want to work across compilers, just use
explicit masks).
Anyway, for subsurface, I think we can mix "bool" between C and C++
code, but there really are reasons not to go overboard.
Linus
More information about the subsurface
mailing list