What is the difference between int++ and ++int? [duplicate]

ぐ巨炮叔叔 提交于 2019-12-01 15:57:39

问题


Possible Duplicate:
What is the difference between ++i and i++
pre Decrement vs. post Decrement

Yes I'm a noob, but I completely forgot what they both do.

I know, however, that int++ just adds one to the value of int.

So, what is ++int?

Thank you.


回答1:


If you're talking about C (or C-like languages), it's exactly the same unless you use the value:

int a = 10;
int b = a++;

In that case, a becomes 11 and b is set to 10. That's post-increment - you increment after use.

If you change that line above to:

int b = ++a;

then a still becomes 11 but so does b. That's because it's pre-increment - you increment before use.

Note that it's not quite the same thing for C++ classes, there are efficiencies that can be had by preferring one over the other. But since you're talking about integers, C++ acts the same as C.




回答2:


a++ will return a and increment it, ++a will increment a and return it:

a = 5; b = a++; // b = 5, a = 6

a = 5; b = ++a; // b = 6, a = 6




回答3:


Every expression in C or C++ has a type, a value, and possible side-effects.

int i;
++i;

The type of ++i is int. The side-effect is to increment i. The value of the expression is the new value of i.

int i;
i++;

The type of i++ is int. The side-effect is to increment i. The value of the expression is the old value of i.




回答4:


it's the preincrement operator

nice explanation here



来源:https://stackoverflow.com/questions/9917564/what-is-the-difference-between-int-and-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!