Precedence and associativity of operators in C -


this question has answer here:

please have @ following code snippet:

int = 10, b;   b = (a) + (++a);                       //2   printf("b = %d\n", b);   

output:

b = 22   

in statement 2, there 4 distinct operators. out of () has highest precedence. since associativity of () operator left right why b = 22 , not 21 ?

$ gcc --version   gcc (ubuntu/linaro 4.7.3-1ubuntu1) 4.7.3 

b = (a) + (++a); 

this has undefined behavior.

quoting c99 standard (actually n1256 draft), 6.5p2:

between previous , next sequence point object shall have stored value modified @ once evaluation of expression. furthermore, prior value shall read determine value stored.

this expression both reads value of a , updates it, , read operation (the lhs of +) not used determine value stored write operation (the rhs of +).

the 2011 iso c standard (quoting n1570 draft) states differently, same meaning:

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.

(a) value computation using value of a; (a++) side effect on a. since order of evaluation of operands of + not specified, these 2 operations unsequenced relative each other.

so it's not matter of order of evaluation being undefined -- behavior undefined, , not limited possibilities of operands of + operator being evaluated in either of 2 possible orders.

and no, parentheses don't change this.

section 3 of comp.lang.c faq explains well.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -