In this code snippet, what values do a and i have respectively and why?
int i = 1;
int a = i++;
Does a == 1 or a == 2 ?
In this code snippet, what values do a and i have respectively and why?
int i = 1;
int a = i++;
Does a == 1 or a == 2 ?
A will be one. This is called a post-increment. The variable i is only increased after being used. The opposite is called a pre-increment.
a==1, i++ returns the value of i and then increments it. FYI, if you had ++i the opposite would be true, i would be incremented and then the value would be returned.
int i = 1;
i now has the value 1.
int a = i++;
a has the value of i++, which is 1 (i++ returns 1, then it increases the value of i by 1). i now increases with 1 and becomes 2.
At this point, a == 1, i == 2.