+ 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 ?
7 Answers
+ 2
+ 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;
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.
0
Justice , I would like to see the implementation of your proposal đ
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.
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....
- 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???