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
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++;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With