task in increment , decrement , printf() , why these are evaluated in this manner in C -
this question has answer here:
#include<stdio.h> #include<stdlib.h> int main() { int a=3; //case 1 printf("%d %d %d\n",(--a),(a--),(--a));//output 0 2 0 printf("%d\n",a);//here final value of 'a' //end of case 1 a=3; //case 2 printf("%d\n",(++a)+(a--)-(--a));//output 5 value of 2 printf("%d\n",a);//here final value of 'a' //end of case 2 a=3; //case 3 printf("%d\n",(++a)*(a--)*(--a));//output 48 value of 2 printf("%d\n",a);//here final value of 'a' //end of case 3 //case 4 int i=3,j; i= ++i * i++ * ++i; printf("%d\n",i);//output 81 i=3; j= ++i * i++ * ++i; printf("%d\n",j);//output 80 //end of case 4 return 0; }
i clear how these outputs coming spent 3 hours in gazing @ , want know in detail why being taken or evaluated in manner.
this tricky 1 judge printf evaluates right left first --a pushes 2 , next a-- pushes 2 again post becomes 1 , --a makes first 0 , pushes , guessed output 0 2 2 surprise 0 2 0 final value of a=0 given places used pre increment , decrement . why happens ?
this take normal evaluation , printing made 4 in a-- again taken 4 , again in --a taken 3 4+4-3=5 done final value of happens 1 -1 post decrement done in middle becomes 2 again why happening ?
this execution same above , takes 4 * 4 * 3 = 48 , final value 2.
this not tricky want answer in detail figured first becomes 4 in ++i , @ i++ becomes 4 , @ ++i becomes 5 , 4*4*5 = 80 in case store in , becomes 80 , 1 +1 post increment. can 1 clear decision when store 80 in variable j , saw 80 , final value 6.
so logically judged printing , viewing things in these cases , yet more based in come can go on posting want @ assembly level how happening , why takes post increment separate state or how can different programs can judged generically each cannot keep printing , finding pattern can me in detail here. , worst part executed code in ideone , gives me different output can test @ ideone if interested why these happens please tell me breaking head @ thing 3 hours me professionals.and used gcc compiler.
this undefined behavior modifying variable more 1 in between sequence points
in in case within same expression not allowed. can not rely on output of program @ all.
from c99
draft standard 6.5.2
:
between previous , next sequence point object shall have stored value modified @ once evaluation of expression. furthermore, prior value shall read determine value stored.
it cites following code examples being undefined:
i = ++i + 1; a[i++] = i;
Comments
Post a Comment