Search code examples
c#incrementcompiler-optimization

Compiler Optimization & Increments


Does compiler optimization cause a problem with code like this? Specifically, can the auto-increments be replied upon to evaulate in the correct order?

uint result = (array[i++] << 16) | (array[i++] << 8) | array[i++];

Solution

  • Yes; this is specified.

    The spec says:

    Operands in an expression are evaluated from left to right. For example, in F(i) + G(i++) * H(i), method F is called using the old value of i, then method G is called with the old value of i, and, finally, method H is called with the new value of i. This is separate from and unrelated to operator precedence.