[英]Calling a function through a function pointer - dereference the pointer or not? What's the difference?
I tried both - C
and C++
and both work fine.我尝试了C
和C++
,两者都工作正常。
I'm kinda new to function pointers and here's 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's not relevant to the question
}
So, what's the difference between那么,两者有什么区别
sort_ptr( arr1, 5 );
and和
(*sort_ptr)( arr2, 5 );
Both seems to work (no errors, no warnings, sorted arrays) and I'm kinda confused.两者似乎都有效(没有错误,没有警告,排序的数组),我有点困惑。 Which one is the correct one or they both are correct?哪一个是正确的,或者两者都是正确的?
sort_ptr( arr1, 5 );
and和
(*sort_ptr)( arr2, 5 );
Both are correct.两者都是正确的。 In fact, you can put as many asterisks you want and they are all correct:实际上,您可以输入任意数量的星号,它们都是正确的:
(*****sort_ptr)( arr2, 5 );
The name of function decays to a pointer to a function.函数的名称衰减为指向函数的指针。 So dereferencing it repeatedly is going to produce the same pointer.所以反复取消引用它会产生相同的指针。
As far as the compiler is concerned, sort_ptr
and (*sort_ptr)
are identical.就编译器而言, sort_ptr
和(*sort_ptr)
是相同的。 If sort_ptr
really is a pointer, however, explicitly dereferencing it makes things a lot clearer for the reader.但是,如果sort_ptr
确实是一个指针,那么显式取消引用它会使读者更清楚。 In general;一般来说; there is one case where the fact that you can call a function directly on a pointer to function is useful: in templates, where it makes a pointer to function a functional object, which behaves exactly like a class with an operator()()
.在一种情况下,您可以直接在指向函数的指针上调用函数这一事实很有用:在模板中,它使指向函数的指针成为功能对象,其行为与带有operator()()
的类完全相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.