mpen
mpen

Reputation: 283355

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?

Upvotes: 4

Views: 2787

Answers (2)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422320

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.

Upvotes: 8

Phil Hunt
Phil Hunt

Reputation: 8541

Under Visual Studio 2008/.NET Framework 3.5 on Windows, index is incremented before recursiveFunction is called. This sample app prints "index = 1" to the console.

class Program
{
    private int index = 0;

    private static void Main()
    {
        new Program().TryMe();
    }

    private void TryMe()
    {
        var list = new List<int>();
        list.Add(1);
        list.Add(2);

        list[index++] = ReturnZero();
    }

    private int ReturnZero()
    {
        Console.WriteLine(string.Format("index = {0}", index));
        return 0;
    }
}

Upvotes: 5

Related Questions