piątek, 3 stycznia 2014

Short-circuit evaluation

Something to start with - short-circuit evaluation.

Feature present in many programming languages (esp. "die" invocation in Perl), C and C++ are no exception to this.

Let's take first example:

if ((1 == a) && (2 == b))
{
   // do sth.
}

The point here is - when 'a' is not equal to 1 then second condition is not checked at all.
Therefore first outcome of SCE is minimization of operation and there is no need for explicit constructions like:

if (1 == a)
{
   if (2 == b)
   {
      // do sth.
   }
}

Similarly for "or" operation e.g.:
if ((1 == a) || (2 == b))
{
   // do sth.
}

When 'a' is equal to 1 second is not checked.
Above examples shows only minor effect of run-time optimization.

More difficult situation can appear when condition contains function invocation (or expression) that has side effect, e.g.:
if ((1 == a) || change_value(&b))
{
   // do sth.
}
bool change_value(int *b)
{
   if (*b > 0)
   {
      --*b;
   }
   return *b > 0;
}

When 'a' is equal to 1 then there will be no function invocation and consequently no change to 'b' value.



SCE behavior is a must for C and C++ compilers as it is stated explicitly in standard:
  • for C
  1. "Logical AND operator" - "If the first operand compares equal to 0, the second operand is not evaluated."
  2. "Logical OR operator" - "If the first operand compares unequal to 0, the second operand is not evaluated."
  • for C++
  1. "Logical AND operator" - "Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false."
  2. "Logical OR operator" - "Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true."

References


Brak komentarzy:

Prześlij komentarz