Closed Bug 669581 Opened 13 years ago Closed 13 years ago

Prefix increment operator precedence seems wrong

Categories

(Core :: JavaScript Engine, defect)

All
Other
defect
Not set
normal

Tracking

()

RESOLVED INVALID

People

(Reporter: ezra, Unassigned)

Details

User Agent: Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0
Build ID: 20110615151330

Steps to reproduce:

var a=1;
var b = ++a + ++a;


Actual results:

b is 5


Expected results:

b should be 6
a starts at 1.  The first ++a sets a=2 and returns 2.  The second ++a sets a=3 and returns 3.  2+3 = 5.

This is the case in every single JS engine.  I don't know why you thought it should be 6, exactly....
Status: UNCONFIRMED → RESOLVED
Closed: 13 years ago
Resolution: --- → INVALID
in C and C++ the result is 6.

That's why I thought the JS engine might be doing something wrong.
In C and C++ the result is undefined and so can be anything.

http://www.kuzbass.ru:8086/docs/isocpp/expr.html


-4- Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.*

Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined. [Example:

    i = v[i++];                     //  the behavior is unspecified
    i = 7, i++, i++;                //   i  becomes  9

    i = ++i + 1;                    //  the behavior is unspecified
    i = i + 1;                      //  the value of  i  is incremented
Oh, I see.  In C and C++, the behavior of that expression is actually undefined because while operator precedence is defined the order in which side effects take place between sequence points is not defined.  Depending on your compiler and optimization settings, this code could return 6, 5, 4, 3, or 2.  Per spec, the code is simply invalid C code, and the compiler can return any number it wants, set your machine on fire, etc.  See http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.15 and http://en.wikipedia.org/wiki/Sequence_point (the latter mentions that this applies to C as well).  gcc's -Wsequence-point will apparently warn you about code like this.

JS doesn't have this problem; it actually defines what number you should get in this situation.
You need to log in before you can comment on or make changes to this bug.