Code: #include<stdio.h> int main(void) { int a=7; int b=++a * ++a; printf("\n\n%d",b); return (0); } The O/P: 72 PROGRAM NO 2: ============= Code: #include<stdio.h> int main(void) { int a=7,b; b=++a * ++a; printf("\n\n%d",b); return (0); } The O/P: 81 Why is the different O/Ps from the same program ??? Just because of separate declaration and defination.... ??!!! Plz explain this a little bit more clearly and if possible then provide me some links to follow these types of increment decrement operations done in C...
What compiler you are using. I used Visual Studio 8 and it gave me 81 in both the cases which is what it should be.
> which is what it should be Nope, the program uses side effects on the same variable more than once in the same equation so the results are undefined. ++a means take the value of a, having increased a SOME TIME BEFORE. That time is specified up to a point, but it is not precisely defined. Therefore individual compiler writers are free to implement pre-increment as they see fit, and that could well account for the difference between "int b; b=++a * ++a;" and "int b=++a * ++a;" In the first case, the expression being evaluated is "b=++a*++a", whereas in the latter the expression being evaluated is just "++a*++a". Two common implementations of ++a are (a) bump it and take its value as a single operation and (b) process all pre-effects; evaluate the expression using fixed values; process all post-effects. Visual Studio takes the latter approach, so ++a * ++a is evaluated as "increment a twice, then multiply 9 by 9". Compilers that do the former might evaluate the expression by bumping a and taking its value (8), then the same again (9), then multiply the results, giving 72. BOTH ARE CORRECT BY THE C++ STANDARD. So the net effect of all this is that if you're going to use side effects, make sure you know EXACTLY what you're doing otherwise you'll get unexpected results. "a++" is a good shortcut for "a=a+1", and fine if you use it ONCE in an expression, but as soon as you do it twice or more you get undefined results, and this is worth avoiding.
The disassembly shows this is what's happening in Visual Studio (my comments prefixed with "--"): Code: int a=7; 0041210E mov dword ptr [a],7 int b=++a * ++a; 00412115 mov eax,dword ptr [a] 00412118 add eax,1 0041211B mov dword ptr [a],eax -- eax=a; eax+=1; a=eax; 0041211E mov ecx,dword ptr [a] 00412121 add ecx,1 00412124 mov dword ptr [a],ecx -- ecx=a; ecx+=1; a=ecx; 00412127 mov edx,dword ptr [a] 0041212A imul edx,dword ptr [a] 0041212E mov dword ptr [b],edx -- edx=a; edx*=a; a=edx;
Which version? If you compile to assembly (RTFM to find out how) then you should see the differences in the code between the two statements, which will show why you get 72 for one and 81 for the other.