问题
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