Post/pre increments in 'printf' [duplicate]

烈酒焚心 提交于 2019-12-22 01:08:00

问题


Possible Duplicates:
Output of multiple post and pre increments in one statement
Post-increment and pre-increment in 'for' loop

The following code snippet

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

gives the output

1 0

I can understand that, but the following

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

gives the output

2 2

Can someone explain me the second behavior?


回答1:


Both printfs invoke undefined-behavior. See this : Undefined behavior and sequence points

Quoted from this link:

In short, undefined behaviour means anything can happen from daemons flying out of your nose to your girlfriend getting pregnant.

For newbies : Don't ever try to modify values of your variables twice or more in a function call argument-list. For details, click here to know what it means. :-)




回答2:


They're both undefined behaviour. Modifying the variable i more than once is undefined. Also, C++ or C? You need to make up your mind as the behaviour of pre-increment I believe is different between them.




回答3:


You got what called 'undefined behaviour', because you are changing the same variable more than once between sequence points. Another compiler can give you different results.



来源:https://stackoverflow.com/questions/4706404/post-pre-increments-in-printf

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