Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer increment and chaining precedence in C#

Tags:

c#

pointers

I saw this piece of C# code in one of the msdn articles:

using System; class Test
{
   public static unsafe void Main() 
   {
      int* fib = stackalloc int[100];
      int* p = fib;
      *p++ = *p++ = 1;
      for (int i=2; i<100; ++i, ++p)
         *p = p[-1] + p[-2];
      for (int i=0; i<10; ++i)
         Console.WriteLine (fib[i]);
   }
}

I am fairly new to pointers. I understand most of this code, but it would be great if someone can help me understand this line in the above code in more detail:

*p++ = *p++ = 1 
like image 253
Hari Menon Avatar asked Jul 11 '10 09:07

Hari Menon


3 Answers

That's just a lazy (others would say idiomatic) way to write

*p++ = 1;
*p++ = *p++;

or, perhaps better to understand:

*p=1;
p++;
*p=1;
p++;
like image 85
Doc Brown Avatar answered Nov 11 '22 03:11

Doc Brown


In C# *p++ = *p++ = 1; is equivalent to:

 *p++ = 1;
 *p++ = 1;

So the first 2 elements of the array (which is what p pointed to originally) are initialized to 1, and p is left pointing to the third element (element 2 using zero-based notation).

As an aside, note that a similar statement in C/C++ would have undefined behavior since the pointer p is modified more than once without an intervening 'sequence point'. However, C# evaluates the expression in a well defined manner.

like image 2
Michael Burr Avatar answered Nov 11 '22 01:11

Michael Burr


You need to break things down:

*p++

This is doing two things: dereference p and a post increment. I.e. show what is at the address p now (or assign to it) and after increment it (to the next memory location).

So two of these are allowing assignment to the initial and second memory locations (while leaving p referring to the third).

C# allows chained assignments: a = b = 2 assigns 2 to both a and b.

NB don't try this in C or C++, modifying the same thing (p) more than once in a single expression is undefined. But C# does define this.

like image 2
Richard Avatar answered Nov 11 '22 03:11

Richard