+ 1
Output of C++ code
Why is the value of t underdetermined? #include <iostream> using namespace std; int main() { int s = 20; int t = s++ + --s; cout << s << " " << t << endl; return 0; }
4 odpowiedzi
+ 3
Let's say it was t=s++, how would you do it?:
increment s
t=s-1
Or
t=s
increment s
Now, let's take the original line
How would you do it?:
increment s
decrement s
t = (s-1) + s
Or
decrement s
t = s + s
increment s
Or
tmp = s
increment s
t = tmp + (s-1)
decrement s
Or
Any other method it comes to your mind
As you can see there are many ways you can do that, and C++ (like C) decided not to make a standard way to do it such that compilers can optimize things better, choosing what better fits for them
Expressions like this are said to have an undefined behavior, the grammar is correct, but the meaning is ambigous, so you should avoid them
+ 3
That's a good question.
Mostly it has to do with how compilers work. There's some wonky things that happen when you use these increment and decrement operators all in the same expression, namely in how compilers handle their order. The increment and decrement operators really have no preferred order in which to be evaluated, and this is reflected in how the compiler handles them. Results can vary from compiler to compiler as well, as there really is no standard method of ordering them.
0
Strange, I thought that the behavior would be for s to be decremented, then use the value of s, then increment s, but it seems prefix and postfix are less useful than I had originally thought…
0
C++ will not know operator like ++ +
because when it's bushes operator to stack of computer's memory will consider it isn't balanced .
change the method of calculation by part it to steps.