Reputation: 43
I was using function returning bool as a condition in if statement in Arduino:
bool conditionFunc(){
return true;
}
void setup(){}
void loop(){
if (conditionFunc){
}
}
In my opinion I should do:
if (conditionFunc()){ //added ()
doSometing;
}
But the first one didn't cause any error during verifying, and code worked (according to my client - I didn't build a circuit - it was simple job so I didn't have to do it). I found it by accident. I don't have any variable named conditionFunc. In my opinion error should be discovered during verifying in Arduino IDE.
I'm confused. Did I miss something when I was learning c++, and the both solutions are OK? Maybe this is caused by the way c++ is interpreted by Arduino? As I said I didn't see it in action, but I don't know why my client would lay about something he wants to work properly. At least it should cause problem during compilation (verification in Arduino IDE)
Upvotes: 0
Views: 394
Reputation: 254691
The first converts the function into a function pointer, and tests whether that pointer is non-null. It always is, since every function has a non-null address, so it will always doSomething
.
So the code will compile, and might appear to "work" if the condition is usually true; but it might go wrong when the condition is false but the program carries on to doSomething
anyway.
Upvotes: 5