bug with ++i ??

 

when i do some test with mql4 by this script:

 

int i = 0;

Print(i++ + i++);  // result is "1"

i = 0; 

Print(++i + ++i); // result is "4" not "3"

 

 and i had do the same thing in JavaScript, "++i + ++i" => 3;

is that a bug? 

 

unbelievable :) Even in MT5!

well, it's the way the cpp compiler analyses and executes expressions, it obviously performs pre-increment first on the whole expression.

whether this is a bug or not, depends on the definition of the cpp standard which MQ doesn't follow completely anyway, so it can be interpreted either way. perhaps it is even a bug in optimizer. it is not so uncommon situation, although i haven't seen this behaviour on dozens of c/cpp compilers in almost 30 years :)

however if you use this kind of expressions, it's your own fault: you will have bugs and unpredicted situations in your code.
expressions have to be clean, without pre and post increments if you are using same variable more than once in the expression, with lots of brackets to clearly define the priority of operations etc.
otherwise you will have Don Quixote's issues.

 
ihao: Print(++i + ++i); // result is "4" not "3"
  1. Report it to the service desk. 'MQL5.community - User Memo' - an article about the algorithmic/automated trading in MetaTrader as "right before" isn't the same as "before."
    Increment and decrement operations are applied only to variables, they can't be applied to constants. The prefix increment (++i) and decrement (--k) are applied to the variable right before this variable is used in an expression.

  2. Post-increment (a++) and post-decrement (k--) are applied to the variable right after this variable is used in an expression.

    They warned you not to go there: Arithmetic Operations - MQL4 Documentation

    Important Notice

    int i=5;
    int k = i++ + ++i;

    Computational problems may occur while moving the above expression from one programming environment to another one (for example, from Borland C++ to MQL4). In general, the order of computations depends on the compiler implementation. In practice, there are two ways to implement the post-decrement (post-increment):

    1.The post-decrement (post-increment) is applied to the variable after calculating the whole expression.

    2.The post-decrement (post-increment) is applied to the variable immediately at the operation.

    Currently the first way of post-decrement (post-increment) calculation is implemented in MQL4. But even knowing this peculiarity, it is not recommended to experiment with its use.

Reason: