简体   繁体   English

将函数调用为fun()和fun之间有什么区别?

[英]what is the difference between calling a function as fun() and fun?

I came across a piece of code which is as below 我遇到了一段代码,如下所示

qsort(array, 10, sizeof(int), sort);

Here sort is again a function. 这里排序又是一个功能。 But I was always under the impression that any function which is called should have () after the function name or was I missing something. 但我总是认为任何被调用的函数都应该在函数名之后有()或者我错过了什么。

I just wanted to know how will this work and what are the differences in calling functions like these. 我只是想知道这将如何工作以及调用这些函数的不同之处。 Thanks! 谢谢!

qsort(array, 10, sizeof(int), sort);

这会传递一个指向函数“sort”的指针,以便函数“qsort”可以调用此函数。

That function is not called it is passed as a function pointer. 该函数未被调用它作为函数指针传递。 see Function Pointers in C and C++ 请参阅C和C ++中的函数指针

You are passing a pointer to the function sort to function qsort , so that qsort can use the function as comparison function. 您正在将指向函数sort的指针传递给qsort函数,以便qsort可以将该函数用作比较函数。

The correct syntax should include a & before sort (since sort is a function, not a pointer, so we need to reference it), but the compiler "adds" it for you anyway. 正确的语法应该包括& before sort (因为sort是一个函数,而不是指针,所以我们需要引用它),但编译器无论如何都会“添加”它。

If you look at the C grammar (eg in the C Standard) you find that there is an operator written as () , which is the function call operator . 如果查看C语法(例如在C标准中),您会发现有一个运算符写为() ,它是函数调用运算符 It is similar to the array subscript operator [] in that it is applied to an identifier, in this case, the name of the function. 它类似于数组下标operator [] ,因为它应用于标识符,在本例中是函数的名称。 If the identifier for a function is not followed by the function call operator, the identifier represents a pointer to that function. 如果函数的标识符未被函数调用操作符跟随,则标识符表示指向该函数的指针 So now it becomes clear, what qsort 's last arg is: a pointer to the comparison function. 所以现在很清楚, qsort的最后一个arg是什么:指向比较函数的指针。 Whenever it needs to compare two elements it calls the function pointed to by its last arg. 每当需要比较两个元素时,它就会调用最后一个arg指向的函数。

The sort function in your example is termed a callback function, qsort calls it back (several times, with different arguments). 您的示例中的sort函数称为回调函数, qsort将其调回(多次,使用不同的参数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM