+ 1

why the output is not what i expect

here is the code #include <stdio.h> int main () { int p = 7; int x = ++p - --p ; printf("x %d\n",x); return 0; } i expect x to be 1 but the output in my compiler is 0 and idk why. my logic is that first there is ++p so the first valur is 8 than the seconde --p so it's 7, so 8-7=1. am i wrong ?

2nd Jun 2022, 9:47 AM
Rabii ABOUAISSA
Rabii ABOUAISSA - avatar
7 Answers
2nd Jun 2022, 10:32 AM
Jayakrishna 🇼🇳
+ 2
â˜ș Yes you are wrong 😉 x = ++p - --p; 1. ++p => x=8- --8; 2. --p => x=7-7; 3. 7-7 => x=0; This is called "undefined behavior", that is, on various devices or operating systems, the compiler will determine the effectiveness of the actions performed by itself (there is no strict sequence, which is faster, it will do it). 😉 More interesting expression: x = ++p - p--; 1. ++p => x=8-8--; 2. p-- => x=7-8; 3. 7-8 => x=-1;
2nd Jun 2022, 11:53 AM
Solo
Solo - avatar
0
You can put that block of code in a loop and have it print a number each time to see what it is doing.
2nd Jun 2022, 10:27 AM
Justice
Justice - avatar
0
Justice , I would like to see the implementation of your proposal 😉
2nd Jun 2022, 12:12 PM
Solo
Solo - avatar
0
Solo I'm not here to do the work for the person asking, I was just to give a suggestion for debugging. Print statements can be helpful when not fully understanding algorithms we have created.
2nd Jun 2022, 12:31 PM
Justice
Justice - avatar
0
Solo How is it not possible to add a print statement? The asker is literally printing something in the piece of code they provided. Also, loops are one of the first things people tend to learn for a programming language. If they're doing math operations, loops such as a while or for loop isn't that far off....
2nd Jun 2022, 1:07 PM
Justice
Justice - avatar
- 1
Justice, the suggested tips should be productive, but your advice is not possible for a novice programmer to implement. That's why I turned to you. Are you able to implement what you suggested???
2nd Jun 2022, 1:03 PM
Solo
Solo - avatar