Is there an explanation for inline operators in “k += c += k += c;”?

What is the explanation for the result from the following operation?

k += c += k += c;

I was trying to understand the output result from the following code:

int k = 10;
int c = 30;
k += c += k += c;
//k=80 instead of 110
//c=70

and currently I am struggling with understanding why the result for "k" is 80. Why is assigning k=40 not working (actually Visual Studio tells me that that value is not being used elsewhere)?

Why is k 80 and not 110?

If I split the operation to:

k+=c;
c+=k;
k+=c;

the result is k=110.

I was trying to look through the CIL, but I am not so profound in interpreting generated CIL and can not get a few details:

 // [11 13 - 11 24]
IL_0001: ldc.i4.s     10
IL_0003: stloc.0      // k

// [12 13 - 12 24]
IL_0004: ldc.i4.s 30
IL_0006: stloc.1 // c

// [13 13 - 13 30]
IL_0007: ldloc.0 // k expect to be 10
IL_0008: ldloc.1 // c
IL_0009: ldloc.0 // k why do we need the second load?
IL_000a: ldloc.1 // c
IL_000b: add // I expect it to be 40
IL_000c: dup // What for?
IL_000d: stloc.0 // k - expected to be 40
IL_000e: add
IL_000f: dup // I presume the “magic” happens here
IL_0010: stloc.1 // c = 70
IL_0011: add
IL_0012: stloc.0 // k = 80???


#c-sharp

1 Likes1.40 GEEK