Search code examples
clogical-operatorsshort-circuiting

What is the meaning of this C code? [short-circuit evaluation]


Jeffrey Stedfast offered several functions that calculates the nearest power of 2. One of the functions has code as follows:

static uint32_t
nearest_pow (uint32_t num)
{
  uint32_t j, k;
  (j = num & 0xFFFF0000) || (j = num); // What is this?
  ...
}

To fully understand the code, I tried changing the line to:

  j = num & 0xFFFF0000;
  j = j | (j = num);

Accidentally, I got a correct result. However, when I applied such transformation to the next lines (not included in my quotation), I got a wrong result. It turned out that I misunderstood the meaning of the code.

What is the meaning of (j = num & 0xFFFF0000) || (j = num);?

Actually, I need to convert the function to other programming languages.


Solution

  • || is the logical or -operator. It has a short-circuiting behaviour such that if the left side is true, the right side is not evaluated (because the result of the logical or is known to be true already from the true left side).

    In this case it is used in a roundabout way to provide a fallback assignment j = num if the first assignment j = num & 0xFFFF0000 is zero (“false”). So, first the upper two bytes (mask 0xFFFF0000) of num are assigned to j. If this is zero (“false”), i.e., the upper two bytes didn't have any 1-bits, then num is assigned to j.

    Effectively this means “assign to j the upper two bytes of num if they are non-zero, otherwise assign to j the lower two bytes of num”.