Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does int++ get incremented?

I've got a line of code,

list[index++] = recursiveFunction();

Does index get incremented before or after the call to recursiveFunction?

like image 634
mpen Avatar asked Dec 12 '22 17:12

mpen


1 Answers

The increment operation is executed before the function call. See http://msdn.microsoft.com/en-us/library/aa691322(v=VS.71).aspx. Note that this is not relevant to the precedence and associativity of operators.

The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators (Section 7.2.1).

Operands in an expression are evaluated from left to right. For example, in F(i) + G(i++) * H(i), method F is called using the old value of i, then method G is called with the old value of i, and, finally, method H is called with the new value of i. This is separate from and unrelated to operator precedence.

Operator precedence and associativity only affect the way operators are bound to operands. The question here talks about side effects of the evaluation of operands.

using System;

class Obj {
   public bool Incremented {get;set;}
   public static Obj operator ++ (Obj o) {
     Console.WriteLine("Increment operator is executed.");
     return new Obj {Incremented = true};
   }
}

class L {
  public int this[Obj o] {
    set { Console.WriteLine("Assignment called with " + 
            (o.Incremented ? "incremented" : "original") + " indexer value."); }
  }

}
class Test{
  static void Main() {
    Obj o = new Obj();
    L l = new L();
    l[o++] = Func();
  }

  static int Func() {
    Console.WriteLine("Function call.");
    return 10;
  }
}

Prints:

Increment operator is executed.
Function call.
Assignment called with original indexer value.

This behavior is clearly specified in the specification and should be identical in any conforming compiler.

like image 146
mmx Avatar answered Dec 29 '22 01:12

mmx