I have two questions about this code...
Why is that at line 10 it starts keeping the current value. For example,
int a = 7
(a += 4)
Which is 11
is brought over to the next line of code (a -= 4)
now making it 7
. Instead of just using it initial declaration for the variable a
which is 7
. How come I don't get 3
? Is the =
in the +=
operator changing what I initially declared it in the beginning of the code ? Does a
still hold the value 7
in memory, or does those statements change that?
At the last MessageBox.Show()
statement. I increment a
by 1
using a++
. However, I get the same value I had for the previous MessageBox.Show()
. How come it didn't increment ??
This is the code:
private void button1_Click(object sender, EventArgs e)
{
int a = 7;
int b = 3;
MessageBox.Show((a + b).ToString(), "a+b");
MessageBox.Show((a - b).ToString(), "a-b");
MessageBox.Show((a * b).ToString(), "a*b");
MessageBox.Show((a / b).ToString(), "a/b");
MessageBox.Show((a += 4).ToString(), "a+=4"); //adds 4 to a
MessageBox.Show((a -= 4).ToString(), "a-=4"); //substracts 4 from a
MessageBox.Show((a *= 4).ToString(), "a*=4"); //multiplies 4 from a
MessageBox.Show(a++.ToString(), "a++"); //adds 1 to a
}
How come I don't get 3 ? Is the "=" in the "+=" operator changing what I initially declared it in the beginning of the code ?
The +=
operator is equivalent to:
a = a + 4
Effectively assigning a new value to a
.
Does "a" still hold the value 7 in memory, or does those statements change that?
It doesn't. After your first assignment, it changes.
At the last MessageBox.Show() statement. I increment "a" by 1 using "a++". However, I get the same value I had for the previous MessageBox.Show(). How come it didn't increment ??
That's what happens when you use ++
as a postfix. The docs say:
The second form is a postfix increment operation. The result of the operation is the value of the operand before it has been incremented.
But, if you use it as a prefix:
MessageBox.Show((++a).ToString(), "++a");
You'll see the updated value, again as the docs say:
The first form is a prefix increment operation. The result of the operation is the value of the operand after it has been incremented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With