Output of multiple post and pre increments in one statement [duplicate]

百般思念 提交于 2019-11-26 07:46:55

问题


This question already has an answer here:

  • Why are these constructs using pre and post-increment undefined behavior? 14 answers
  • int b=0,a=1;b= ++a + ++a; what is the value of b? what is the calculation for it? [duplicate] 2 answers

I\'m new to C language so plz sum1 help me out. A C code written

int i=3;
printf(\"%d\",++i + ++i);

Complier gvs O/P =9. How?
Thanx in advance


回答1:


The results are undefined. You're modifying a variable more than once in an expression (or sequence point to be more accurate).

Modifying a variable more than once between sequence points is undefined, so don't do it.

It might be your compiler, for this particular case decides to evalate ++i + ++i as

  • increment the last ++i , yielding 4, leaving i to be 4
  • increment the first ++i, yielding 5, leaving i to be 5 (as the prior step left i as 4, incrementing it to 5)
  • sum the two values, 4 + 5.

Another compiler, or if you alter the optimization level, or if you change the code slightly, might produce different output.



来源:https://stackoverflow.com/questions/3812850/output-of-multiple-post-and-pre-increments-in-one-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!