boolean

ello all,
i’ve seen to have forgotten how to declare a boolean variable…
any help would be greatly appriceated.
thanks in advanced.
(wow, my spelling is vile)

There is no boolean variable type in C. Most people declare it as char (or unsigned char) and use the value 0 for false and 1 (or any value != 0) for true.

Through the use of #defines and typedefs, you can emulate it, though.

typedef unsigned char bool
#define TRUE 1
#define FALSE 0

Then just use the variable type bool and the values TRUE and FALSE.

There isn’t an explicit boolean type.
Typically, you use “char”

do the boolean functions (and & not) work this way?

I’m not 100% sure if this wouldn’t work, but my original thought would be it wouldn’t.

char boolVar = 1;

if(boolVar)
{
//Do this
}

but for && and || and != they all work the same:

char var1 = 1;
char var2 = 0;

if(var1 == 1 && var2 != 1)
{
//do this
}

Use this (http://www.lysator.liu.se/c/bwk-tutor.html) as a reference and you should be OK.

In reply to previous concerns:
As long as you use the logical operators (&& || !) instead of the bitwise ones (& | ~ ^), you shold be ok.

If you need to use == and !=, I would recomend using one of this macros around the operands (the values being compared).


// CBOOL Converts to BOOLean
#define CBOOL(val) ((val) ? TRUE : FALSE)
// LOGically EQuivalent
#define LOG_EQ(val1,val2) (CBOOL(val1) == CBOOL(val2))
// LOGically Not EQuivalent
#define LOG_NEQ(val1,val2) (CBOOL(val1) != CBOOL(val2))

You can get rid of the #defines by using an enum:

typedef enum {TRUE=1, FALSE=0} bool;

There’s also a small practical benefit for this approach:

Some compilers will be able to do some extra type-checking against the enum values, and warn you if you accidentily try to do something like “bool b_Var = 5”.

Assuming you’re using MPLAB/CBOT, I think the #define method would be best. The method to use though is completely based on what makes you happy.

There’s honestly countless number of ways to accomplish though. Like I said though, I think the #define method is best not to mention, very short on the lines side