DEV Community

Discussion on: The difference between x++ and ++x

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!;)