I have a doubt about this code:
int i, x, z = 4, y = 1;
i = x = z += y++;
Which is the value of i
? Can we know that value or not?
I have a doubt about this code:
int i, x, z = 4, y = 1;
i = x = z += y++;
Which is the value of i
? Can we know that value or not?
First of all, have you tested if this compiles at all?
If not, then why?
Unless you write some code that invokes UB, compiler, regarding basic syntax of the language, has most of the answers you'll ever need. Please test it yourself, and if it's still not clear, or behaves weirdly, then it's something worth asking.
In this case, it's valid, so let's go through it.
#include <iostream>
int main() {
int i, x, z = 4, y = 1;
i = x = z += y++;
std::cout << "i=" << i << std::endl;
}
I compiled, ran it, and here's the result:
$ g++ test.cpp -o test
$ ./test
i=5
So, what is actually going on in this line?
i = x = z += y++;
First of all, it's easier to understand when you add parentheses so it's perfectly obvious what is evaluated and when:
i = (x = (z += (y++)));
i
is a result of assignment to x
;x
is a result of addition assignment to z
;z
is a result of z +
(y
post increment);You can then work your way backwards through the list, and will arrive at the correct result:
z + y
, which is 4 + 1
, or 5
;i = x = z;
(or, form that's too obvious, i = (x = z);
), and that means that i
, just like x
is 5.Whatever you do, please don't actually write code like this, while it's easy to deconstruct, it's not something that is easy to understand at a first glance, and that, more often than not, causes confusion.
Can we know that value or not?
Yes.
Which is the value of
i
?
5
since you add y
to i
, where their values are 4 (since i
gets assigned the value of z
, which is 4) and 1 respectively.
y
is incremented after z
has been initialized. It's incremented in the following statement, as @john commented.
As @LightnessInOrbit commented, this is not good code. Forget about it and move on.
Yes the value of i is 5.
Just trace the code.
y++
post increement i,e first assign the value then increement so Y= 4
. Next
z += y
shorthand operation i,e.., z= z + y
,initially z=4 so 5 = 4+ 1
so Z=5
x = z
i.e, x = 5 Next
i = x
i.e, i = 5
.