unexpected behaviour of pre and post increment in c language gcc compiler [duplicate]

时光毁灭记忆、已成空白 提交于 2019-12-13 09:17:25

问题


If n has the value 5 then output:

printf("%d %d", n++, ++n); //should be 5 and 7

But I get as output 6 and 7.


回答1:


Multiple unsequenced modifications result to such kind of Undefined Behavior. There are tons of results if you search for it, e.g. this question.

Next time compile with all warnings enabled, like this:

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
main.c:6:22: warning: multiple unsequenced modifications to 'n' [-Wunsequenced]
    printf("%d %d", n++, ++n); 
                     ^   ~~



回答2:


printf() invoke undefined-behavior. Please have a look at Undefined Behavior and Sequence Points

It's not a good practice to modify values of your variables twice or more in a function call argument-list



来源:https://stackoverflow.com/questions/43935693/unexpected-behaviour-of-pre-and-post-increment-in-c-language-gcc-compiler

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