Log in

View Full Version : boolean


atmaturen
20-12-2004, 08:13
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)

Joe Ross
20-12-2004, 09:25
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.

Mark McLeod
20-12-2004, 09:26
i've seen to have forgotten how to declare a boolean variable...
There isn't an explicit boolean type.
Typically, you use "char"

atmaturen
20-12-2004, 17:40
do the boolean functions (and & not) work this way?

colt527
20-12-2004, 17:48
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
}

Mike Betts
20-12-2004, 17:52
do the boolean functions (and & not) work this way?
Use this (http://www.lysator.liu.se/c/bwk-tutor.html) as a reference and you should be OK.

Astronouth7303
21-12-2004, 17:56
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))

jude
28-12-2004, 00:28
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".


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.

Raven_Writer
28-12-2004, 12:49
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*