Unexpected behavior of pre and post increment in c language compiler

If n has a value of 5, then print:

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

But I get a weekend of 6 and 7.

-2
c increment output post-increment pre-increment
source share
2 answers

Numerous imperceptible modifications lead to this kind of Undefined Behavior. There are tons of results if you are looking for them, for example. this is a question .

Next time compile all included warnings, for example:

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

printf () calls undefined -behavior. Please see Undefined Behavior and sequence points.

It is not good practice to change the values โ€‹โ€‹of your variables twice or more in the function argument list

0
source share

All Articles