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

2

-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.

Pistoia answered 12/5, 2017 at 10:37 Comment(2)
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.Grigsby
unexpected behaviour Actually, it's undefined behaviour. The order of evaluation of function arguments is not defined.Disforest
C
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); 
                     ^   ~~
Chose answered 12/5, 2017 at 10:42 Comment(0)
S
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

Sherikasherill answered 12/5, 2017 at 10:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.