Home  >  Article  >  What is the difference between a++ and ++a?

What is the difference between a++ and ++a?

烟雨青岚
烟雨青岚Original
2020-07-14 09:31:0285042browse

The difference is: the timing of incrementing the value of variable "a" is different; "a" and "a" are both auto-increment operators; "a" takes the value first and then increments it "1"; "a" is first incremented by "1" and then taken.

What is the difference between a++ and ++a?

a and a are both auto-increment operators. The difference is that the timing of incrementing the value of variable a is different. a is taken first and then incremented. a is auto-incremented first and then taken.

Example

For example: Suppose x=3, y=4;

(1) (x) (x)=8

Explanation: For the first (x), because x takes the value first and then increments, the value obtained by (x) is 3, and then x increments, at this time x=4; for the first Two (x), because x is incremented first and then takes the value, so the value obtained by (x) is 5. At this time, x=5, so the result is 8.

(2) (x )/3 (--y)*2-(x--)%6 (y )*3-(y--)

1 6-4 9-4=8

Explanation: First (x) takes the value 3, then x=4; then (--y) takes the value 3, at this time y=3; Then (x--) takes the value 4, then x=3; then (y) takes the value 3, then y=4; finally (y--) takes the value 4, then y=3;

Note :() can increase the arithmetic priority, so the expression in the brackets is calculated first, but the value of x is x, and then x is incremented.

Key points: The operation priority is very high

Interview question:

int  i = 10
i  =  i++ ;

At this time, what is the value of i?

Answer: The value of input i is 10

Analysis: First, the value of i is 10, then i is incremented, at this time, i=11, and finally the value is assigned. So the final output value of i is 10.

For more related knowledge, please visit PHP Chinese website! !

The above is the detailed content of What is the difference between a++ and ++a?. 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