Since the first answer didn't fully go into the example at hand, I'll elaborate on this, because it's, at first, a tricky subject IMO.
int a = 1, b, c;
This declares three int variables: a
, b
and c
. It also initializes a
with the value 1. b
and c
receive the default start value for ints, so 0.
As the first answer mentioned, fun1(int d)
copies the value of the variable passed to it into a local variable, but does not alter the original variable. What's the matter with ++d
and d++
, though? This got to do with the order in which operations get performed. ++d
takes the value of d
, increases it by one, then assigns it back to d
. d++
on the other hand first assigns the value of d
back to d
(thus returning it from a function if used in a return statement) before increasing it by one. Why is this relevant?
Let's keep in mind fun1(a)
works with a local variable so does not, in fact, alter variable a
. ++d
increases the local variable by 1, so it's now 2. Then d++
returns the current value of d
(2), and then increases the local variable by 1 again -- but this doesnt't get stored anywhere outside of the function fun1()
. Hence, the variable b
has now the value 2.
c = fun2(b);
is a different case, though. Here, we pass a reference to the variable b into the function. So ++d
doesn't just increase the value of a local variable but instead increases the value of b
, it's now 3. d++
returns this value to c (so it gets assigned 3), but also increases b
by 1 again to 4. Why? Because d
is a reference to b
.
Our ultimate values are hence: a = 1
, b = 4
, c = 3
, and 1 + 4 + 3 = 8.