DEV Community

Cover image for The difference between x++ and ++x

The difference between x++ and ++x

Basti Ortiz on October 20, 2018

The laziness and practicality of a programmer Let's face it. Programmers are paid to type some magic into a screen that eventually becom...
Collapse
 
fxedel profile image
Felix Edelmann • Edited

Nice explanation! However, I'm not happy with the last line of your last code example:

button.addEventListener('click', () => span.innerHTML = ++numberOfPresses); 
Enter fullscreen mode Exit fullscreen mode

The occurrence of both => and = make the expression somehow difficult to read.

One could use parentheses to emphasize the assignment:

button.addEventListener('click', () => (span.innerHTML = ++numberOfPresses)); 
Enter fullscreen mode Exit fullscreen mode

Or maybe one could spend a new line:

button.addEventListener('click',
  () => (span.innerHTML = ++numberOfPresses)
);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
somedood profile image
Basti Ortiz

I totally agree with you there. I don't have the best code formatting skills, so that's nice of you to bring up. I'll go edit the format right now. Thanks for the suggestion!

Collapse
 
jonasroessum profile image
Jonas Røssum

I suggest using prettier, since it is have become a well accepted and easily readable code format.

You can try it out here:
prettier.io/playground/

Thread Thread
 
somedood profile image
Basti Ortiz

As nice as a standardized code format sounds, I just can't agree with some of them. I'm looking at you, "Standard" JS. I prefer to have my own coding style. I think of coding as an "art form", where my coding style is my "signature".

Don't let that discourage you from using Prettier, though. I totally agree with its objective to standardize code formats for the sake of productivity and readability.

Thread Thread
 
jonasroessum profile image
Jonas Røssum

Oh man, I also despited Standard when I first tried it! What a frustrating experience I.

For some reason though, my experience with prettier has been almost the opposite. I think it's partly due to it having sane and very readable defaults and partly because I've set it up to match my personal code style (e.g. no semi-colons).

I've discovered how having automatic formatting in my editor is priceless for productivity! No more fiddling with indents and line breaks. Recently I've found myself using Format On Save in Visual Studio Code more often, as it just makes having clean code that much easier.

Thread Thread
 
somedood profile image
Basti Ortiz

To me, I primarily disagreed with how Standard JS treats semicolons. I mean just look at this absurdity! I don't like how it is being too clever with the format.

;[1, 2, 3].forEach(bar)
;(function () {
  window.alert('ok')
}())
;`hello`.indexOf('o')

Of course, this is an extreme example. Even their documentation discourages lines of code that begin with [, (, and the like. Nonetheless, I just feel strange when they have the audacity to call it "Standard" JS in the face of some weird syntax that is too clever.

Thread Thread
 
canlitvizlemeli profile image
Canlı Tv İzlemeli

I tried this method on tv izle my platform and I was very successful. Thank you.

Collapse
 
codevault profile image
Sergiu Mureşan • Edited

Great explanation! I found it quite difficult to explain this feature (albeit in C) in a video or post and you've done a really good job at it!

If you have ever joined programming Facebook groups you will see one question related to this topic pop up quite often:

// What will the value of x be after executing these statements?
let x = 1;
x = x++ + ++x + x++;

The answer: depends. In JavaScript I get 7, probably because they are evaluated from left to right (and because it is an interpreted environment) but in C or Java you can get some really unexpected results and in most languages it is undefined behaviour.

Collapse
 
ivanovicdanijel profile image
danijel

Undefined behaviour!?
In Java,
x = 1 + 3 + 3 = 7
What is undefined?

Collapse
 
codevault profile image
Sergiu Mureşan

Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

In Java they are also evaluated from left to right (unless you have a x += 1 instead of x++) then it gets confusing.

This answer goes more in-depth about undefined behaviour in C/C++

Thread Thread
 
ivanovicdanijel profile image
danijel

Thanks a lot!;)

Collapse
 
xowap profile image
Rémy 🤖

I think that the length of this article for something seemingly so simple is the proof that using ++ should be forbidden (by example, it does not exist in Python).

Here's another article on an alternate method:


To increment a variable, simply use the following syntax:

i += 1

Here's an example on how to use in a for loop:

const stuff = ['a', 'b', 'c', 'd'];

for (let i = 0; i < stuff.length; i += 1) {
    console.log(stuff[i]);
}

Pitfalls: none

When to use this method: well anytime you need to increment by one.

Collapse
 
fpuffer profile image
Frank Puffer

No. The += operator is used to add any number to a given variable. Increment is more elementary than addition. When used in programming, it normally has a completely different semantics than addition. Therefore it does make sense if a language has a special operator for it. It makes the language more expressive and the code at least potentially more readable.

The complications addressed in this thread do not result from the existence of the increment operator itself but from the fact that there are two of them in certain languages.

Collapse
 
xowap profile image
Rémy 🤖

Well good point on increment theoretically being a different operation than addition, however in practice I think in terms of produced bugs.

If you do stuff like

const a = ['a', 'b', 'c'];
let i = 0;

while (a[i] !== undefined) {
    doStuff(a[i++]);
}

At the moment you start digging into it and do some quick copy/pasta for debugging purposes:

const a = ['a', 'b', 'c'];
let i = 0;

while (a[i] !== undefined) {
    doStuff(a[i++]);
    console.log(a[i++]);
}

You're done because you've created a bug.

So I know you're going to explain to me all the rules to follow not to create bugs and the rigorous way you have to work with ++. However if you just don't use it then you don't need to use those rules and that's many less issues to load your head with. Also it's pretty easy to forbid it in the linter so you also help juniors not making mistakes.

Unlike what you said, the real issue is not that you can do both operations but rather that you're playing with side-effects. Neither of those operators are good.

In case you're curious about how it goes under the hood, I've compiled two example functions. A first one which does a ++:

char get_next_char_pp(char* str, int i) {
    return str[++i];
}

The produced ASM is the following

get_next_char_pp:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-8], rdi
        mov     DWORD PTR [rbp-12], esi
        add     DWORD PTR [rbp-12], 1
        mov     eax, DWORD PTR [rbp-12]
        movsx   rdx, eax
        mov     rax, QWORD PTR [rbp-8]
        add     rax, rdx
        movzx   eax, BYTE PTR [rax]
        pop     rbp
        ret

Now using the += 1 method:

char get_next_char_add(char *str, int i) {
    i += 1;
    return str[i];
}
get_next_char_add:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-8], rdi
        mov     DWORD PTR [rbp-12], esi
        add     DWORD PTR [rbp-12], 1
        mov     eax, DWORD PTR [rbp-12]
        movsx   rdx, eax
        mov     rax, QWORD PTR [rbp-8]
        add     rax, rdx
        movzx   eax, BYTE PTR [rax]
        pop     rbp
        ret

As you can see, CPU-wise it is totally identical. The compiler actually just splits your line in two implicitly. And as the Zen of Python says: Explicit is better than implicit.

Hence my strong advocacy against the ++ operator in any language. It is a useless and harmful operator, source of headaches and bugs.

Thread Thread
 
fpuffer profile image
Frank Puffer

Yes, the main issue is mutability. The ++ operator is actually a hidden assignment. In most modern languages there are few use cases for incrementing variables, mainly because they provide better ways for looping over collections. However I sometimes have to maintain legacy C code where I don't want to miss ++ in for loops.

I believe that += is only slightly better when it comes to copy/paste errors. You can also do this (at least in C++ and Java - not sure about JS):

while ( ... ) {
    doStuff(a[i += 1]);
    console.log(a[i += 1]);
}

But it looks weird and will hopefully be noticed soon.

Collapse
 
awwsmm profile image
Andrew (he/him)

Additionally, there can be a performance difference between prefix and postfix in some languages. If it doesn't matter to you which one is used, prefix (++i) should be your default. Reference

Collapse
 
somedood profile image
Basti Ortiz • Edited

Someone should make a jsPerf for that. Although I doubt a significant performance difference, it is nonetheless interesting (and exciting) to see the results.

Collapse
 
fabioemsm profile image
Fábio Moreira

It may have, performance implications in some languages. Think of these operators as functions (functors, I believe) as for ++x you'd something like:
public int ++operator (int &x) {
x = x + 1;
return x;
}
And for x++ you have something like
public int operator++ (int &x) {
int tmp = x;
x = x + 1;
return tmp;
}

As you can see, from the second example above, there is one more instruction needed to store the previous value of x and then return it.
But I don't think there is a major impact unless you use it extensively, also todays compilers may or may not predict and optimize the end result.
PS: the examples above only work in languages that have the concept of functors (function operators) like C++ does.

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

One other critical difference in some languages, including C and C++: ++x is one less compiled instruction than x++. That can add up to a notable performance difference in some applications, especially loops. I imagine that would be true of most languages with increment operators.

Yes, your compiler will sometimes optimize that anyway, but it depends on which optimizations you've opted in to, as well as other circumstances. As pythonic as the saying may be, "explicit is better than implicit" is true as a generally universal rule, especially wherever performance is concerned.

Collapse
 
lisabenmore profile image
Lisa Benmore

Great breakdown of the differences! One additional use-case to mention where prefix vs postfix makes a world of difference is when you're passing it into a function. For instance a recursive function where we're using incrementation as a condition:

function count (limit, current = 0) {
  console.log(current);
  if (current < limit) return count(limit, ++current);
  else return current;
}
count(10);
Enter fullscreen mode Exit fullscreen mode

The above will console out 0-10 and return 10. However, if we were to use postfix, we'd have to increment before our if/else statement or else it would be an infinite loop where current is always equal to zero. Obviously, this function is only as an example and wouldn't be very useful in practice, but it was a similar case where I really learned the difference between x++ and ++x ;)

Collapse
 
medhair profile image
medhair

Le pays du Bosphore et plus particulièrement la ville d’Istanbul offrent les conditions parfaites pour une greffe de cheveux turquie

Collapse
 
paul202183 profile image
paul202183

Thank you for sharing your knowledge with this informative post about one of the intricacies of JavaScript. Well-written explanation.luxury replica watches

Collapse
 
floppleus profile image
Roger Flopple

Thank you very much for your great information. It really makes me happy and I am satisfied with the arrangement of your post captain marvel sweater. You are really a talented person I have ever seen. I will keep following you forever.

Collapse
 
knownigeria_ng profile image
KnowNigeria • Edited

Thank you very much for your great information. It really makes me happy and I am satisfied with the arrangement of your post Davido & Offset. You are really a talented person I have ever seen. I will keep following you forever.

Collapse
 
riyasrawther profile image
Riyas Rawther
void main() {
  int y;

  //Prefix  (e.g ++a)
  y =1; 
  print (++y); // Prints the previous (1) value, then adds 1 to it. Output is 2
  print (++y); // Previous value is 2 and adds 1 to it. Output is 3
  print (++y); // Previous value is 3 and adds 1 to it. Output is 4
  //note: The first value will be the initial number + 1. Then incements with 1 each time when it called.
  //Prefix 

  // example
  for (int i = 0; i < 5; ++i){
 print('The values are: ${i}'); 
   // note that the first number will be 0
   // to start from 1 change the ${i} to ${i+1}
 }

}
Collapse
 
trakode profile image
Trakode • Edited

Thank you,

Really very well explained, I'm going to get inspired to explain this to my group on Trakode

Why not in a video conference!

Collapse
 
emilyjuan58 profile image
emilyjuan58

include

int main()
{
int x=5,y=15;
x= x++ + ++y;
y = ++x + ++y;
printf("%d %d",x,y);
return 0;
}
MardamsGreat blog very useful thanks

Collapse
 
riyasrawther profile image
Riyas Rawther

one more Example:

Please visit dartpad.dev/. The default sample code when you open the dart-pad is

void main() {
  for (int i = 0; i < 5; i++) {
    print('hello ${i + 1}');
  }
}

Run the sample code.

Note the line # 3 - print('hello ${i + 1}'); The i + 1 is used because initial value is 0. Now think how to avoid that with our prefix increment ++x.

void main() {
  for (int i = 0; i < 5;) {
    print('hello ${++i}');
  }
}

The output will be same.

Collapse
 
riyasrawther profile image
Riyas Rawther
//DART
void main() {
int x;

//Postfix (e.g a++)
x =1; 
print (x++); // Prints the previous value. Output is 1
print (x++); // Previous value is 1 and adds 1 to it. Output is 2
print (x++); // Previous value is 2 and adds 1 to it. Output is 3
//note: The first value will be the same. Then incements with 1 each time when it called.
//PostFix
// example

for (int i = 0; i < 5; i++){
print('The values are: ${i}'); 
// note that the first number will be 0
// to start from 1 change the ${i} to ${i+1}
}

}
Collapse
 
hcanltv profile image
hcanlıtv az • Edited

I've discovered how having automatic formatting in my editor is priceless for productivity! No more fiddling with indents and line breaks. Recently I've found myself using Format On Save in Visual Studio Code more often, Canlı TV İzle as it just makes having clean code that much easier.

Collapse
 
zarifnet profile image
zarifnet

Thank you for sharing your knowledge with this informative post about one of the intricacies of JavaScript. Well-written explanation. zarif

Collapse
 
netvilox profile image
Netvilox

I love programming but it is a very hard thing, I have tried learning php online every thing was going well till i meet functions and loop.
I wonder how people write a full code for a website like 9jaHob 9jaHob

Collapse
 
isaacleimgruber profile image
IsaacLeimgruber

What was the other post with the psychopath reviewing your code :)

Collapse
 
somedood profile image
Basti Ortiz

I'm sorry, but I don't quite get what you mean. Can you help me out here?

Collapse
 
isaacleimgruber profile image
IsaacLeimgruber

If you find yourself in a situation where it matters whether you write x++ or ++x then maybe you should first consider writing more readable code instead of compact one

Thread Thread
 
somedood profile image
Basti Ortiz

Ah, now I catch your drift. You're definitely not wrong in that regard. 🙂

Also, this post has anything to do with my previous one. Just wanted to share some information on an overlooked feature of the language. That's why I said, "If we want to go crazier," at some point in the article. Compacting the code in a single arrow function is just for those who are crazy and confident enough to do it (like me). I'm a pretty crazy person now that I think about it. I should chill myself out.

Meh, I'm still going to write more articles in the future that introduce crazy syntax and shortcuts when I feel like it. Who knows? Perhaps a maintainer of a minification algorithm would see my articles and improve his/her algorithm just a slight bit more. Every bit counts when you're minifying...

Thread Thread
 
isaacleimgruber profile image
IsaacLeimgruber

Yeah I mean some optimisation are good and some are detrimental to understanding. However I think arrow functions is the first kind :)

Thread Thread
 
somedood profile image
Basti Ortiz

Right you are, my friend! 😉 One has to crawl before they could walk. In this case, one has to type function() {} before they could type () => {}.

Collapse
 
webdva profile image
webdva

Thank you for sharing your knowledge with this informative post about one of the intricacies of JavaScript. Well-written explanation.

Collapse
 
pranto84 profile image
pranto saha

Off topic , but if anyone can , please help,

Is the code are written on code::blocks ?
if written on code::blocks , can anyone sent me the color combination of code::blocks theme.

Collapse
 
l7ucian profile image
Andercou Lucian

I think the shortening can be done with postfix incrementation two, and as long as you adapt the initial value of the counter, it yields the same output.

Collapse
 
tifflabs profile image
tiff

OMG this saved me a big time headache. No one ever explained this properly to me. Thanks mate!

Collapse
 
lobsterpants66 profile image
Chris Shepherd

Personally I just stick to level 1, does the job and easy to understand if you jump languages often.
In an IDE with autocomplete it's only a couple more key presses.

Collapse
 
canlitvcenter profile image
Canlı TV

Egitim gercekten dunya da en onemli gelen konularin basinda geliyor.Egitim de televizyonun onemi de cok onemlidir. tv izle

Collapse
 
taraftariumapk profile image
Canlı Maç İzle Apk

I tried this method on canlitvapk.com/ my platform and I was very successful. Thank you.

Collapse
 
khafidprayoga profile image
Khafid Prayoga

nice

Collapse
 
paul202183 profile image
paul202183

OMG this saved me a big time headache. No one ever explained this properly to me. Thanks matebuy replica YSL handbags

Collapse
 
jackleren profile image
Lerenjack

This is definitely useful information if you want to keep your contacts update and organized. Thank you! Mens Collection

Collapse
 
abhinowkatore profile image
Abhinav Katore

Thank you nice exaplanation