I have boolean vars that I pass to a function. The function accepts the values as bytes.
Everything seems to work fine but I wanted to check that this is actually acceptable and not just a fluke.
In Arduino.h:
typedef uint8_t boolean;
So for the Arduino boolean is defined as an 8 bit integer type.
Casting means explicitly forcing the type of an expression, you are
asking about implicit type conversions, to be pedantic - C and C++ rules
for type-conversions are not kept secret from the world and Google -
for instance http://www.cplusplus.com/doc/tutorial/typecasting/
Thanks for the reply.
I understand about changing floats into ints etc but i was not sure about changing booleans to bytes since using a boolean as byte seems to work. Even when defined as boolean.
the below works and this hah me a little confused.
boolean var = false;
myFunction (var);
.
.
.
void myFunction (byte var2)
{
// value of var2 = 0;
}
I was not sure if the above was actually correct or not. I thought I may need to cast the var:
boolean var = false;
myFunction (var);
.
.
.
void myFunction (boolean var2)
{
byte var3;
var3 = (byte) var2;
}
I did Google this and originally didn''t find any specific answers. However, just tried a slightly different search and found this:
http://forum.arduino.cc/index.php/topic,27250.0.html
bool and boolean are not the same thing.
michinyon:
bool and boolean are not the same thing.
edited the previous post
michinyon:
bool and boolean are not the same thing.
That's something I didn't know! Since I only use bool, and since I only check it against true or false, it works just like I thought it should. But occasionally, I'll end up with a boolean because I grabbed some code from the forum. For the benefit of anyone wondering what the difference is, I wrote this little test sketch to show it:
bool b;
boolean bn;
void setup() {
Serial.begin(115200); // opens serial port, sets data rate to 9600 bps
for (int i = -2; i < 3; i += 2) {
b = i;
bn = i;
Serial.print(b);
if (b) {
Serial.println(" b is true");
}
else {
Serial.println(" b is false");
}
Serial.print(bn);
if (bn) {
Serial.println(" bn is true");
}
else {
Serial.println(" bn is false");
}
}
}
void loop() {
}
And the results are:
1 b is true
254 bn is true
0 b is false
0 bn is false
1 b is true
2 bn is true