Re: Boolean data type?



Martin Wells <warint@xxxxxxxxxx> writes:
I come from C++, and there's a type called "bool" in C++. It works
exactly like any other integer type except that when promoted, it
either becomes a one or a zero, so you can you bitwise operators as if
they were logical operators:

bool a = 5, b = 6;

if (a == b) DoSomething; /* This will execute */

What type is commonly used in C for playing around with boolean
values?

<http://www.c-faq.com/>, section 9.

I'm writing code for an embedded systems project so I'll *really* have
to watch how much memory I'm using... so would it be wise to be
returning "int" from functions that I would otherwise (in C++) return
a bool from?
[...]

Using a type smaller than int for booleans is likely to save space,
but is also likely (but not certain) to increase code size. If your
CPU can load, store, and manipulate bytes as easily as words, using a
1-byte type makes sense; if not, int is likely to be a good choice.

If you want to have, say, large arrays of booleans, the tradeoffs
change. It might even make sense to store a boolean value in each bit
(but you'll have to write your own bitwise masking and shifting code
to do this -- or find something that's already been written).

Assuming C99's _Bool is not available, my favorite form is something
like:

typedef enum { false, true } bool;

This allows the compiler to decide how big to make a bool. But watch
out for name collisions if another library you're using defines its
own boolean type.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.



Relevant Pages

  • Re: &= for bools?
    ... are Boolean and not bitwise when applied to bool operands (and yes, ... they can be used with bool). ... dealing with one bit, it's a bitwise ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: &= for bools?
    ... operands and logical AND on bool operands." ... are Boolean and not bitwise when applied to bool operands (and yes, ...
    (microsoft.public.dotnet.languages.csharp)
  • [PATCH] drivers/block/DAC960: Converted boolean to bool
    ... Converts 'boolean' to 'bool' and removes the 'boolean' typedef. ... unsigned char CommandOpcode2, ... typedef struct DAC960_SCSI_RequestSense ...
    (Linux-Kernel)
  • [PATCH] drivers/video/sis: Convert to generic boolean
    ... BOOLEAN -> bool ... Have followed all function/variable paths who been converted to 'bool' ... SiS_GetModeID(int VGAEngine, unsigned int VBFlags, int HDisplay, int VDisplay, ...
    (Linux-Kernel)
  • Re: Weird problem calling DLL
    ... afaik a Delphi boolean is not ... always equal to a bool also. ... *neither* language defines the binary representation of the types. ...
    (comp.lang.pascal.delphi.misc)