A Question about the OR ( || ) Operator.

If I do something like this:

boolean b;
b = MyFunctionX() || MyFunctionY();

is it assured that BOTH MyFunctionX and MyFunctionY get called. or does it stop processing the expression if MyFunctionX returns a logical true value?

I recall that for some languages the expression evaluation actually stops in an OR expression as soon as it gets a logical true value, the reasoning being that it "doesn't need" to evaluate the rest since it already has a true value.

How does it work for the Arduino sketches?

edit... Why should it even do any evaluation in the first place, it's not in an "if" or anything to cause it to care?- I'm thinking it will just assign the current value of MyFunctionX() (be it True or False) to b and be done.

But why don't you write a quick sketch to test it?

edit... see Reply #4

It will call MyFunctionX. If that returns zero it will call MyFunctionY. If both return zero then b will be false otherwise it will be true.

I recall that for some languages the expression evaluation actually stops in an OR expression as soon as it gets a logical true value, the reasoning being that it "doesn't need" to evaluate the rest since it already has a true value.

This is one of those languages.

How does it work for the Arduino sketches?

Same as in C++ if there is any doubt about this or future questions.

I take back what I said above. Change the return values of the functions in the below code, and b prints a "1" if either of the functions returns "true":

boolean b;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  
  b = MyFunctionX() || MyFunctionY();
  Serial.println(b);

}

void loop() {
  // put your main code here, to run repeatedly: 
  
}

bool MyFunctionX()
{
  return false;
}

bool MyFunctionY()
{
  return true;
}

The key-phrase is "short circuit evaluation".

That reminds me of the old joke:

"What do you mean, I've got a short-circuit? Well, lengthen it!"

:grinning:

The samantics of || and && are that the second operand is guaranteed only to
be evaluated if necessary. That's not the same thing as happening not to be
evaluated because of compiler optimization... Testing what one compiler does can
never reveal the full semantics of a language feature (for one thing compilers have
bugs).

Thus it is valid code to do this:

  if (object != NULL && object->field > 7)

since the dereferencing of the pointer object can only happen if it has
been tested as non-NULL.

This is also known as lazy evaluation, as opposed to eager evaluation. C
is nearly all eagerly evaluated, || and && are exceptions.