Search code examples
c#.netloopsxor

What's the point in this xor magic defining the upper bound of a loop?


I've stumbled upon this piece of code without any comments:

int delay = 5;
int maxDelay = 5 * (3 ^ 5); // << what's this xor magic?
while( Something && delay < maxDelay ) {
    Thread.Sleep( delay );
    delay *= 3;
}

What's the point in that 3 ^ 5? That's "3 xor 5" which is six, not anything interesting like maybe one third of Int32.MaxValue. Why not just write 6 instead? I guess it has to do something with the fact that the result is then multiplied by 5 and also the value is multiplied by 3 on each iteration.

Is that some well-known pattern? What does it do?


Solution

  • He meant Math.Pow(3, 5) but ^ is not the power operator (which does not exist in C#). This is a bug.

    That makes sense because in the loop he is increasing delay exponentially. So the exponential upper bound makes sense.

    I think this is bad style even if it worked. It is not obvious how often the loop will run. He should have used a normal for loop and computed delay freshly inside the loop instead of running it along the loop incrementally.