i want a complete explanation for this... please

vignesh1988i's Avatar
Banned
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);
SaswatPadhi's Avatar, Join Date: May 2009
~ Б0ЯИ Τ0 С0δЭ ~
This one has undefined behaviour, since it modifies the lvalue i without intervening sequence points.

See : http://en.wikipedia.org/wiki/Sequence_point.
vignesh1988i's Avatar
Banned
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......

so only am asking the correct explanation with stack implementation...... plzzzz
vignesh1988i's Avatar
Banned
sorry , 'j' is giving me 60.... pl. explain with stack
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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.