Casting boolean to int

Is this going to work?

boolean varA = true;
int varB = 2;
int varC;


varC = varB - (int)varA;

Expected result would be c = 1.

Try it and see.

On some chips/systems, TRUE is all bits set. Then the answer would be 3.

Apart from experimentation, why would you want to do this?

Hi

boolean values (in C anyway) are just stored as 1 for true and 0 for false

You can see this by trying:

if(1)//means if true, i.e will always execute
{
//some code
}

or
while(1) //infinite loop
{
//infinite loop here
}

My guess is if you cast one to an int you would just get 1 or 0

GoForSmoke:
On some chips/systems, TRUE is all bits set. Then the answer would be 3.

The C++ standard guarentees true to be cast to a 1.

That's nice. What part of "some chips/systems" is stumping you?

I am sure I've seen at least one Basic and maybe one C that set -all- the bits. Yet in -every- case I have seen, 0 is false and non-zero is true.

Try this in setup():

if (-1) Serial.println( "-1 is TRUE" );

See if it don't work.

GoForSmoke:
What part of "some chips/systems" is stumping you?

I assume you are taking exception to the text I quoted rather than what I wrote. In that case I will respond more directly to the quote... Some non-compliant C++ compilers used for some chips/systems may not correctly cast a true to 1. We don't care about those chips/systems. The compiler used for Arduino is a compilant C++ compiler so true is guarenteed to cast to 1.

if (-1) Serial.println( "-1 is TRUE" );

What does that have to do with casting a bool[ean] value?

kustom:
Is this going to work?

boolean varA = true;

int varB = 2;
int varC;

varC = varB - (int)varA;




Expected result would be c = 1.

Whether or not it works, I wouldn't be doing it. Apart from the arguments about whether or not true is equivalent to 1, it is like subtracting apples from oranges. Your expression would be more correctly (readably) written as:

varC = varB;
if (varA)
  varC--;

Or even:

varC = varB - (varA ? 1  : 0);

Do u even need to cast it?

Take a look at this thread:

There is a big difference between code that merely works, and is maintainable, readable, easily fixed in the future, etc.