Output of C++ code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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; }

25th Jul 2021, 11:20 PM
Edward Finkelstein
Edward Finkelstein - avatar
4 Answers
+ 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
26th Jul 2021, 12:39 AM
Angelo
Angelo - avatar
+ 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.
26th Jul 2021, 12:44 AM
BootInk
BootInk - avatar
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…
26th Jul 2021, 5:16 AM
Edward Finkelstein
Edward Finkelstein - avatar
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.
26th Jul 2021, 7:55 AM
Anas Mohammed Sarhan Saif
Anas Mohammed Sarhan Saif - avatar