the statement i++ increases i after the statement is executed.
in contrast to ++i which increases i before the statement is executed.
so the code
int i=1;
i=i++;
does:
- (line 1) initialize variable iwith value 1.
- (line 2) insert the current value of i(1) to the variablei(it is not yet changed).
- (line 2) increases ifrom 1 to 2.
the code
int i=1;
i++;
does:
- (line 1) initialize variable iwith value 1.
- (line 2) increases ifrom 1 to 2.
The difference is more clear in those examples:
example a
int i=1;
i=10+(i++);
std::cout << i << std::endl;
does:
- (line 1) initialize variable iwith value 1.
- (line 2) compute the result of 10 plus the current value of i(1) (result 11).
- (line 2) insert result 11 of last computation to i.
- (line 2) increases ifrom 11 to 12.
- (line 3) print 12.
example b
int i=1;
int j = i++
i=10+j;
std::cout << i << std::endl;
does:
- (line 1) initialize variable iwith value 1.
- (line 2) insert the current value of i(=1) toj.
- (line 2) increases ifrom 1 to 2
- (line 3) compute the result of 10 plus the current value of j(=1) (result 11).
- (line 3) insert result 11 of last computation to i.
- (line 3) print 11
example c
int i=1;
int j = i++
i=10+i;
std::cout << i << std::endl;
does:
- (line 1) initialize variable iwith value 1.
- (line 2) insert the current value of i(=1) toj.
- (line 2) increases ifrom 1 to 2
- (line 3) compute the result of 10 plus the current value of i(=2) (result 12).
- (line 3) insert result 112 of last computation to i.
- (line 3) print 12
summery
All of the following codes leave i with the same value at the end:
a)
int i = 1;
i++;
b)
int i = 1;
i = i++;
c)
int i = 1;
int k = i++;