# i want a complete explanation for this... please

Discussion in 'C' started by vignesh1988i, Oct 2, 2009.

1. ### vignesh1988iBanned

Joined:
Sep 19, 2009
Messages:
72
0
Trophy Points:
0
Location:
Chennai
pl.. explain a complete stack explanation for the below expression and say me the final value for j...

int i=16,j;
j=i-- + i-- + --i + i--;
printf("%d",j);

2. ### SaswatPadhi~ Б0ЯИ Τ0 С0δЭ ~

Joined:
May 5, 2009
Messages:
1,342
55
Trophy Points:
0
Occupation:
STUDENT !
Location:
Orissa, INDIA
http://www.crackingforfun.blogspot.com
3. ### vignesh1988iBanned

Joined:
Sep 19, 2009
Messages:
72
0
Trophy Points:
0
Location:
Chennai
but this is giving the value of 'i' is 60... but for me when am working out 'i' is only 57 for me...

however this operation should have surely made use of STACK data structure......:smug:

so only am asking the correct explanation with stack implementation...... plzzzz

4. ### vignesh1988iBanned

Joined:
Sep 19, 2009
Messages:
72
0
Trophy Points:
0
Location:
Chennai
sorry , 'j' is giving me 60.... pl. explain with stack

5. ### xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,009
203
Trophy Points:
63
Occupation:
Senior Support Engineer
Location:
England
Any explanation would be completely compiler specific. This expression gives undefined behaviour - that is the only possible answer. The explanation for that is what Saswat has already said: it modifies an lvalue more than once without an intervening sequence point. So to turn this into sensible code that has predictable results you must add sequence points, for example:
Code:
```int i=16,j;
j=i--;
j+=i--;
j+= --i;
j+=i--;
printf("%d",j);
```
which gives the output 57, and i=12 at the end.

Don't know why you want a stack-based explanation; the expression won't necessarily use a stack. In Visual Studio 2008 the result of:
Code:
```int i=16,j;
j=i-- + i-- + --i + i--;
printf("%d",j);
```
is 60, because it separates all side effects out from the equation, doing pre-decrements first and post-decrements after, and is therefore equivalent to:
Code:
```	int i=16,j;
--i;
j=i+i+i+i;
i--;
i--;
```
(note this behaviour is Visual Studio 2008 specific and may not be reflected in other compilers)
and the assembly code generated by the expression is:
Code:
```	j=i-- + i-- + --i + i--;
004117C5  mov         eax,dword ptr [i]
004117C8  sub         eax,1
004117CB  mov         dword ptr [i],eax
004117CE  mov         ecx,dword ptr [i]
004117D1  add         ecx,dword ptr [i]
004117D4  add         ecx,dword ptr [i]
004117D7  add         ecx,dword ptr [i]
004117DA  mov         dword ptr [j],ecx
004117DD  mov         edx,dword ptr [i]
004117E0  sub         edx,1
004117E3  mov         dword ptr [i],edx
004117E6  mov         eax,dword ptr [i]
004117E9  sub         eax,1
004117EC  mov         dword ptr [i],eax
004117EF  mov         ecx,dword ptr [i]
004117F2  sub         ecx,1
004117F5  mov         dword ptr [i],ecx
```
which as you can see involves no stack operations.