Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

int

add

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.

like image 867
user1260584 Avatar asked Mar 29 '12 00:03

user1260584


3 Answers

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.

like image 104
paxdiablo Avatar answered Oct 11 '22 04:10

paxdiablo


it's the preincrement operator

nice explanation here

like image 34
msonsona Avatar answered Oct 11 '22 04:10

msonsona


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

like image 23
iehrlich Avatar answered Oct 11 '22 04:10

iehrlich