in Programming in C
439 views
2 votes
2 votes
#include <stdio.h>
 
int main(void) {
	static int a[10];
	int x=0;
	a[x]=++x;
	printf("%d %d %d",a[0],a[1],a[2]);
	return 0;
}

my doubt here is [ ] has high precedence over ++ which in turn has precedence over =, so i think it a[x] = ++x; is evaluated in 3 phase like,

phase1: a[x] -> (a+x)* -> (a+0)* -> a*

phase2: ++x -> x=1

phase3: a*=1 or a[0]=1

so finally answer should be 1 0 0, but it is giving 0 1 0 as output.

in Programming in C
439 views

5 Comments

edited by
I think "assignment operator evaluates an expression of the RHS and assign the resultant value to a variable of the LHS"  this is the reason behind it.

Hence while executing phase 3 value of x will be also changed on LHS.
0
0
0
0

@Rishabh, 

the link you gave is different qsn, there it is a[x]=x++ //postfix operator, it can give undefined behavior since [ ] and ++(postfix) has equal precedence, but here i have given prefix operator.

though i got the reason, this is because reading the value of the object for any other purpose than determining the value to be stored is also undefined behavior.\

thankyou!!

0
0
thankyou @Hemant @Rishabh.
0
0

Please log in or register to answer this question.

Related questions