<?xml version="1.0"?> <clause number="25.5.6" title="Pointer arithmetic"> <paragraph>In an unsafe context, the + operator (<hyperlink>14.7.4</hyperlink>) and -operator (<hyperlink>14.7.5</hyperlink>) can be applied to values of all pointer types except void*. Thus, for every pointer type T*, the following operators are implicitly defined: <code_example><![CDATA[ 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); ]]></code_example></paragraph> <paragraph>Given an expression P of a pointer type T* and an expression N of type <keyword>int</keyword>, <keyword>uint</keyword>, <keyword>long</keyword>, or <keyword>ulong</keyword>, 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. 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> <paragraph>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). The type of the result is always <keyword>long</keyword>. In effect, P -Q is computed as ((<keyword>long</keyword>)(P) -(<keyword>long</keyword>)(Q)) / sizeof(T). </paragraph> <paragraph> <example>[Example: For example: <code_example><![CDATA[ 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); } } } ]]></code_example>which produces the output: <code_example><![CDATA[ p - q = -14 q - p = 14 ]]></code_example>end example]</example> </paragraph> <paragraph>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. </paragraph> </clause>