1

The following program compiles in the Arduino IDE.

void doSomething(bool) {}

void setup() {      
  doSomething(Serial);
}

void loop() {}

But, as expected, this one doesn't:

class MyClass {};

void doSomething(bool) {}

void setup() {   
  MyClass myClass;
  doSomething(myClass);
}

void loop() {}

The compiler returns the error cannot convert 'MyClass' to 'bool' for argument '1' to 'void doSomething(bool)'


Why is it possible to compile the former? Isn't Serial a normal class instance (of HardwareSerial)? Does it makes any sense to interpret Serial as a bool?

4

HardwareSerial defines operator bool(), which allows it to be used in a boolean context.

| improve this answer | |
  • And what is the purpose of the bool() operator? – noearchimede Aug 22 '17 at 20:57
  • Classes define whether and how their instances can be converted to bool, and what the resulting bool means. In the specific case of HardwareSerial, it means the serial port is ready: "This will only return false if querying the Leonardo's USB CDC serial connection before it is ready." — arduino.cc/en/Serial/IfSerial – deltab Aug 22 '17 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.