Home  >  Article  >  Backend Development  >  The difference between i++ and ++i and examples

The difference between i++ and ++i and examples

angryTom
angryTomOriginal
2020-02-28 10:43:5064512browse

The difference between i++ and ++i and examples

The difference between i and i and examples

The differences between i and i commands are:

1 , The order of assignment is different

i is added first and then assigned; i is assigned first and then added; i and i are both completed in two steps.

Because i is assigned a value in the next step, it can be used as a variable for cascade assignment, i = a =b, that is, i is an lvalue; the next step of i is an auto-increment, not a left-hand value. value.

The understanding of the image can be that i does other things first, and then adds 1 to itself, i first adds 1 to itself, and then does other things.

Recommended learning: c language video tutorial

For example:

a = i, equivalent to i=i 1; a = i;

a = i, which is equivalent to a = i; i=i 1;

2. The efficiency is different

For example, i= 3. b=i means b=3. After completion, let i become 4. b=i means first let i become 4, then b=4, where i is more efficient than i. Generally speaking, in the loop domain, there is no big difference between the two, but you should pay attention to its life cycle and the change of i value in the program flow.

3. i cannot be used as an lvalue, but i can.

The lvalue is the value of the expression corresponding to the object with a certain storage address in the memory, and the rvalue is the value of all expressions that are not lvalues. Generally speaking, an lvalue is a variable that can be placed on the left side of an assignment symbol.

But whether it can be assigned a value is not the basis for distinguishing lvalues ​​from rvalues. For example, C's const lvalues ​​are not assignable; rvalues ​​that are temporary objects may be assigned. The fundamental difference between lvalues ​​and rvalues ​​is whether the address & operator is allowed to obtain the corresponding memory address.

For example:

int i = 0;
int *p1 = &(++i);//正确
int *p2 = &(i++);//错误
++i = 1;//正确
i++ = 1;//错误

PHP Chinese website, a large number of Introduction to Programming tutorials, welcome to learn!

The above is the detailed content of The difference between i++ and ++i and examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn