Yur Nazo
Yur Nazo

Reputation: 33

Incrementing and Decrementing Confusion

I am a little confused about the following behaviour:

int a = 3;
a++;
in b = a;

I understand that when you do a++ it will add a 1 which makes a = 4 and now b equals a so they are both 4.

int c = 3;
int d = c;
c++

But, here it tells me that c is 4 and d is 3. Since c++ makes c = 4; wouldn't d = 4; too?

Upvotes: 1

Views: 88

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1504182

This line:

int d = c;

says "Declare a variable called d, of type int, and make its initial value equal to the current value of d."

It doesn't declare a permanent connection between d and c. It just uses the current value of c for the initial value of d. Assignment works the same way:

int a = 10;
int b = 20; // Irrelevant, really...
b = a;      // This just copies the current value of a (10) into b
a++;
Console.WriteLine(b); // Still 10...

Upvotes: 6

Related Questions