How are function pointers type unsafe
<p>First of all type-safe means that anything that a compiler can catch straight away if done incorrectly.</p>

<p>Now, I heard function pointers are not type safe however whenever I tried to use them incorrectly the compiler did report errors for me. So, how is it type unsafe ?</p>

<p>E.g This is a function prototype that takes in a function pointer</p>

<pre><code>void SortElements(void* MyArray, unsigned int iNumofElems,size_t size, int(*compare_funct)(void* First,void* SecondElem))
</code></pre>

<p>I have defined few functions to pass to it as:</p>

<pre><code>int MySortAsc(void* First, void* Second);
void MyFunct2();
void MyFunct3(void* First);
</code></pre>

<p>The code only compiles for:</p>

<pre><code>SortElements(MyArray, 10, sizeof(DataType), &amp;MySortAsc); //Compiles
SortElements(MyArray, 10, sizeof(DataType), &amp;MyFunct2);  //Fails
</code></pre>

<p>Any idea how can I mis-use function pointers here ?</p>

<p>Is it because of this:</p>

<pre><code>void (*functionPointer)();
...
int integer = 0xFFFFFFFF;     
functionPointer = (void(*)())integer;      
functionPointer();
</code></pre>

<p>Answer:
What I got to see is that function pointers in C++ are type safe. Ofcourse, they can be used in an unsafe manner by casting it incorectly but that does not make them a reason to be called as type unsafe. .NET delegates are strongly typed as well and to me it looks like both are type safe.</p>
