Variants

Variant1

Best

Worst

Average

O(1)

O(1)

O(1)

Time

O(1)

O(1)

O(1)

Space

The result is 0 for Microsoft's Common Language Runtime.Take a look at the IL code:For the first line "var i = 0;", this is what's going on:1. ldc.i4.0: pushes zero as a four byte integer on the stack2. stloc.0: pops the value zero from the stack into iFor the second line "i = i++;", this is what's going on:1. ldloc.0: loads i on the stack2. dup: duplicates the value on the stack (so zero is duplicated)3. ldc.i4.1: pushes one as a four byte integer on the stack4. add.ovf: adds signed integer values from the top of the stack (zero and one) with overflow checking (overflow checking is irrelevant though in this case)5. stloc.0: pops the value one from the top of the stack into i (so 1 == i at this point)6. stloc.0: pops the other value, which was zero, from the top of the stack into i (so 0 == i at this point, since the second top most value from the stack was not changed)So there you go, it's zero.

Variant2

Best

Worst

Average

O(1)

O(1)

O(1)

Time

O(1)

O(1)

O(1)

Space

You might think that the volatile keyword will forbid the kind of behavior exposed in the first variant, but it doesn't.The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.

Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread.This ensures that the most up-to-date value is present in the field at all times.