C side effects in gcc (prefix/postfix operator and precedence) -


i have small c code:

#include<stdio.h> int main()  {     int  z[]= {1,2,3,4,5,6};     int = 2, j;     printf("i=%d  \n",i);       z[i] = i++;      (j=0;j < 6;j++ )        printf ("%d ", z[j]);      printf("\ni=%d \n",i);  } 

output:

i=2   1 2 2 4 5 6  i=3 

the order of precedence evaluate expression first, z[i] evaluated. 2 here, becomes z[2]. next, i++ evaluated i.e 2 yielded , becomes 3. finally, = executed, , 2 (i.e value yielded i++) put z[2]

this explains above output i.e 1 2 2 4 5 6

but if change above code i++ ++i i.e

#include<stdio.h> int main()  {     int  z[]= {1,2,3,4,5,6};     int = 2, j;     printf("i=%d  \n",i);       z[i] = ++i;      (j=0;j < 6;j++ )        printf ("%d ", z[j]);      printf("\ni=%d \n",i);  } 

then output strangely different, is:

i=2   1 2 3 3 5 6  i=3 

if go above precedence (what c spec says [index] bound earlier ++) output should have been 1 2 3 4 5 6.

i wish know why above order of precedence not explains ?

my compiler gcc 4.5.2 on ubuntu 11.04

thanks , regards, kapil

z[i] = ++i; results in undefined behavior:

6.5 expressions
...
2 if side effect on scalar object unsequenced relative either different side effect on same scalar object or value computation using value of same scalar object, behavior undefined. if there multiple allowable orderings of subexpressions of expression, behavior undefined if such unsequenced side effect occurs in of orderings.84)
84) paragraph renders undefined statement expressions such as
     = ++i + 1;     a[i++] = i;
while allowing
     = + 1;     a[i] = i;

note precedence controls grouping of operators , operands; does not control order of evaluation.

the side effect of ++ operator in ++i unsequenced relative [] operator in z[i]; compiler not required evaluate 2 expressions in particular order. note side effect of ++i need not applied after expression evaluated; needs applied before next sequence point.


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -