-2

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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • Please read about rules of sequence points. The behavior is definitely unexpected. You shouldn't change the value of a variable more than 1 time during a function call. – sameera sy May 12 '17 at 10:44
  • 1
    *unexpected behaviour* Actually, it's **undefined behaviour**. The order of evaluation of function arguments is not defined. – Andrew Henle May 12 '17 at 10:45

2 Answers2

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); 
                     ^   ~~
Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

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

Community
  • 1
  • 1
Shrey
  • 98
  • 1
  • 12