开发者

What is the difference between x++ and ++x [duplicate]

开发者 https://www.devze.com 2023-01-25 08:39 出处:网络
This question already has answers here: Closed 12 years ago. Possi开发者_如何转开发ble Duplicate:
This question already has answers here: Closed 12 years ago.

Possi开发者_如何转开发ble Duplicate:

Incrementing in C++ - When to use x++ or ++x?

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


x++ executes the statement and then increments the value.

++x increments the value and then executes the statement.

var x = 1;
var y = x++; // y = 1, x = 2
var z = ++x; // z = 3, x = 3


x++ returns x, then increments it.

++x increments x, then returns it.


++x is higher in the order of operations than x++. ++x happens prior to assignments, but x++ happens after assignments.

For exmaple:

var x = 5;
var a = x++;
// now a == 5, x == 6

And:

var x = 5;
var a = ++x;
// now a == 6, x == 6


If you write y = ++x, the y variable will be assigned after incrementing x.
If you write y = x++, the y variable will be assigned before incrementing x.

If x is 1, the first one will set y to 2; the second will set y to 1.

0

精彩评论

暂无评论...
验证码 换一张
取 消