Jon Jagger
jon@jaggersoft.com
Table of Contents 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Notes DownloadECMA-334 C# Language Specificationpreviousnextprevious at this levelnext at this level 25 Unsafe codeprevious at this levelnext at this level 25.5 Pointers in expressionsprevious at this levelnext at this level 25.5.6 Pointer arithmetic Paragraph 11 In an unsafe context, the + operator (§14.7.4) and -operator (§14.7.5) can be applied to values of all pointer types except void*. 2 Thus, for every pointer type T*, the following operators are implicitly defined:
T* operator +(T* x, int y);  
T* operator +(T* x, uint y);  
T* operator +(T* x, long y);  
T* operator +(T* x, ulong y);  
T* operator +(int x, T* y);  
T* operator +(uint x, T* y);  
T* operator +(long x, T* y);  
T* operator +(ulong x, T* y);  
T* 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);  
Paragraph 21 Given an expression P of a pointer type T* and an expression N of type int, uint, long, or ulong, the expressions P + N and N + P compute the pointer value of type T* that results from adding N * sizeof(T) to the address given by P. 2 Likewise, the expression P -N computes the pointer value of type T* that results from subtracting N * sizeof(T) from the address given by P. Paragraph 31 Given two expressions, P and Q, of a pointer type T*, the expression P -Q computes the difference between the addresses given by P and Q and then divides that difference by sizeof(T). 2 The type of the result is always long. 3 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];  
         
         int* p = &values[1];  
         int* q = &values[15];  
         
         Console.WriteLine("p - q = {0}", p - q);  
         Console.WriteLine("q - p = {0}", q - p);  
      }  
   }  
}  
which produces the output:
p - q = -14  
q - p = 14  
end example]
Paragraph 41 If a pointer arithmetic operation overflows the domain of the pointer type, the result is truncated in an implementation-defined fashion, but no exceptions are produced.
{ JSL }
Jagger Software Ltd
Company # 4070126
VAT # 762 5213 42
Valid HTML 4.01Valid CSS