Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Despite the fact that this is a horrible interview question, it is actually quite interesting:</p> <pre><code>static unsigned char buffer[256]; int main(void) { unsigned char *p, *q; q = (p = buffer) + sizeof(buffer); /* This statement will set p to point to the beginning of buffer and will set q to point to one past the last element of buffer (this is legal) */ while (q - p) /* q - p will start out being 256 and will decrease at an inversely exponential rate: */ { p = buffer; while (!++*p++); /* This is where the interesting part comes in; the prefix increment, dereference, and logical negation operators all have the same precedence and are evaluated **right-to-left**. The postfix operator has a higher precedence. *p starts out at zero, is incremented to 1 by the prefix, and is negated by !. p is incremented by the postfix operator, the condition evaluates to false and the loop terminates with buffer[0] = 1. p is then set to point to buffer[0] again and the loop continues until buffer[0] = 255. This time, the loop succeeds when *p is incremented, becomes 0 and is negated. This causes the loop to run again immediately after p is incremented to point to buffer[1], which is increased to 1. The value 1 is of course negated, p is incremented which doesn't matter because the loop terminates and p is reset to point to buffer[0] again. This process will continue to increment buffer[0] every time, increasing buffer[1] every 256 runs. After 256*255 runs, buffer[0] and buffer[1] will both be 255, the loop will succeed *twice* and buffer[2] will be incremented once, etc. The loop will terminate after about 256^256 runs when all the values in the buffer array are 255 allowing p to be incremented to the end of the array. This will happen sometime after the universe ends, maybe a little sooner on the new Intels ;) */ } return p - q; /* Returns 0 as p == q now */ } </code></pre> <p>Essentially this is a base-256 (assuming 8-bit bytes) counter with 256 digits, the program will exit when the entire counter "rolls over".</p> <p>The reason this is interesting is because the code is actually completely legal C (no undefined or implementation defined behavior that you usually find in these types of questions) and there is actually a legitimate algorithm problem, albeit a little hidden, in the mix. The reason it is a horrible interview question is because I wouldn't expect anyone to remember the precedence and associativity of the operators involved in the while statement. But it does make for a fun and insightful little exercise.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload