Calling a function through a function pointer - dereference a pointer or not? What's the difference?

I tried both C and C++ and both work fine.

I'm new to pointer functions, and here is a simple code that surprised me:

 #include <assert.h> void sort( int* arr, const int N ); int main () { int arr1[] = { 1, 5, 2, 6, 2 }; int arr2[] = { 1, 5, 2, 6, 2 }; void (*sort_ptr)( int*, const int) = sort; sort_ptr( arr1, 5 ); (*sort_ptr)( arr2, 5 ); assert( arr1[0] == 1 && arr1[1] == 2 && arr1[2] == 2 && arr1[3] == 5 && arr1[4] == 6 ); assert( arr2[0] == 1 && arr2[1] == 2 && arr2[2] == 2 && arr2[3] == 5 && arr2[4] == 6 ); return 0; } void sort( int* arr, const int N ) { // sorting the array, it not relevant to the question } 

So what's the difference between

 sort_ptr( arr1, 5 ); 

and

 (*sort_ptr)( arr2, 5 ); 

Both seem to work (no errors, no warnings, sorted arrays), and I'm a bit confused. Which one is correct, or are both correct?

+7
source share
2 answers
 sort_ptr( arr1, 5 ); 

and

 (*sort_ptr)( arr2, 5 ); 

Both are correct. In fact, you can put as many stars as you want, and they are all correct:

 (*****sort_ptr)( arr2, 5 ); 

The name of the function splits into a pointer to the function. Therefore, dereferencing it will repeatedly produce the same pointer.

+15
source

As for the compiler, sort_ptr and (*sort_ptr) identical. If sort_ptr indeed a pointer, however, by explicitly dereferencing this, this makes things more readable to the reader. Generally; There is one case when the fact that you can call a function directly by a pointer to a function is useful: in templates, where it creates a pointer to the functioning of a functional object that behaves exactly like a class with operator()() .

+2
source

All Articles