If parenthesis has a higher precedence then why is increment operator solved first?

前端 未结 5 1768
梦谈多话
梦谈多话 2020-11-27 05:21

I have a single line code,

int a = 10;
a = ++a * ( ++a + 5);

My expected output was 12 * (11 + 5) = 192 ,but I got 187

5条回答
  •  天涯浪人
    2020-11-27 06:13

      int a = 10;
      a = ++a * ( ++a + 5);
    

    above kind of expressions are always evaluated in left to right fashion be it C or JAVA

    in this case it is solving like this 11*(12+5) which results in 11*17 = 187 // w.r.t java

    but if it we solve the same expression w.r.t C-language

    then the answer gets changed as the way of evaluation changes

    in c first pre-increment/pre-decrement happens ,so if "N" no of times pre inc/dec are there in the expression then inc/dec will happen first "N" no of times

    then the same value will be substituted in each ocurrence of the variable in the expression and the expression value is calculated and after that post increment/decrement happens

    i.e a gets incremented to 11 then again 12 as there are two incrementation for a in the expression and then the expression is evaluated as

    12*(12+5)=12*17=204 //w.r.t C-language

提交回复
热议问题