13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 25 Unsafe codeT* operator –(T* x, int y);T* operator –(T* x, uint y);T* operator –(T* x, long y);T* operator –(T* x, ulong y);long operator –(T* x, T* y);Given an expression P of a pointer type T* and an expression N of type int, uint, long, or ulong, theexpressions P + N and N + P compute the pointer value of type T* that results from addingN * sizeof(T) to the address given by P. Likewise, the expression P – N computes the pointer value oftype T* that results from subtracting N * sizeof(T) from the address given by P.Given two expressions, P and Q, of a pointer type T*, the expression P – Q computes the differencebetween the addresses given by P and Q and then divides that difference by sizeof(T). The type of theresult is always long. In effect, P - Q is computed as ((long)(P) - (long)(Q)) / sizeof(T).[Example: For example:using System;class Test{static void Main() {unsafe {int* values = stackalloc int[20];}}which produces the output:p - q = -14q - p = 14}int* p = &values[1];int* q = &values[15];Console.WriteLine("p - q = {0}", p - q);Console.WriteLine("q - p = {0}", q - p);end example]If a pointer arithmetic operation overflows the domain of the pointer type, the result is truncated in animplementation-defined fashion, but no exceptions are produced.25.5.7 Pointer comparisonIn an unsafe context, the ==, !=, , operators (§14.9) can be applied to values of all pointertypes. The pointer comparison operators are:bool operator ==(void* x, void* y);bool operator !=(void* x, void* y);bool operator (void* x, void* y);bool operator =(void* x, void* y);Because an implicit conversion exists from any pointer type to the void* type, operands of any pointer typecan be compared using these operators. The comparison operators compare the addresses given by the twooperands as if they were unsigned integers.25.5.8 The sizeof operatorThe sizeof operator returns the number of bytes occupied by a variable of a given type. The type specifiedas an operand to sizeof must be an unmanaged-type (§25.2).sizeof-expression:sizeof ( unmanaged-type )327

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!