DEV Community

Cover image for Difference between n++ and ++n?
Kopal
Kopal

Posted on

Difference between n++ and ++n?

Understanding Increment Operations:

Before we delve into post-increment and pre-increment, let's clarify what an increment operation is in the context of programming. Simply put, an increment operation is used to increase the value of a variable by 1. It's like counting one step forward.

Imagine you have a variable **n **set to 5. If you want to increase its value by 1, there are two main ways to do it: post-increment and pre-increment.

Post-increment (n++):

Post-increment is like saying, "Use the current value of n, and after you've used it, increase it by 1."

For example, if you have n = 5, and you write x = n++, what happens? x gets the current value of n (which is 5), and then, as a polite gesture, n increases to 6. So, x gets 5, and n becomes 6.

int n = 5;
int x = n++;  // x gets 5, n becomes 6. 

Enter fullscreen mode Exit fullscreen mode

Pre-increment (++n):

Pre-increment, on the other hand, is more direct. It's like saying, "Increase the value of n by 1 first, and then use the new value."

Suppose n = 5. If you write x = ++n, this time, n becomes 6 immediately, and x receives that new value. So, x gets 6, and n is also 6.

int n = 5;
int x = ++n;  // n becomes 6, and x gets 6.
Enter fullscreen mode Exit fullscreen mode

Choosing Between Post-increment and Pre-increment:

Now that you understand how post-increment and pre-increment work, you might wonder when to use which.

In most cases, it depends on your specific programming needs. If you want to use the current value of a variable and then increment it, post-increment (n++) is the way to go. On the other hand, if you need the incremented value right away, pre-increment (++n) is more efficient.

Conclusion:

In programming, post-increment (n++) uses the current value before increasing it, while pre-increment (++n) immediately provides the updated value. Mastering these concepts is a valuable skill for writing efficient code. Happy coding!

Top comments (3)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Good stuff.

Word of caution: Not every language/library implement these unary operators the same. For example, .Net implementations are identical, so using pre- or post- is irrelevant, in say, a for() loop.

C++, on the other hand (at least a decade ago when I last used it), generally has a higher cost for the post- operation. In C++, post- operations duplicate the object, then increment itself, then return the unincremented copy. This is why I got into the habit of using pre- operations in for() loops.

for (int i = 0; i < NUM_ITEMS; ++i)
{
   ...
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kopal__ profile image
Kopal

Great Insights. Thanks for sharing.

Collapse
 
ranggakd profile image
Retiago Drago

It can be great to refer what language you use in here