简体   繁体   English

为什么函数原型在不同的功能块中?

[英]Why is the function prototype inside a different function block?

I am trying to understand C, by going through K&R. 我试图了解C,通过K&R。 I have trouble understanding this code for two functions found in the book: 我无法理解本书中的两个函数的代码:

void qsort(int v[], int left, int right){
int i, last;

void swap(int v[], int i, int j);

if (left >= right)
    return;

swap(v, left, (left+right)/2);

last = left;

for ( i = left+1; i<=right; i++)
    if (v[i]<v[left])
        swap(v,++last, i);

swap(v,left,last);
qsort(v,left,last-1);
qsort(v,last+1,right);
}


void swap(int v[], int i, int j){

    int temp;

    temp = v[i];
    v[i] = v[j];
    v[j] = temp;
}

These two function perform a quicksort on a given array. 这两个函数对给定的数组执行快速排序。 In the main function I created an int array and called qsort. 在main函数中,我创建了一个int数组并调用了qsort。 It compiled fine and ran fine. 它编译得很好并且运行良好。 My question is, why is the prototype for swap() put in the function qsort() and not before main()? 我的问题是,为什么swap()的原型放在函数qsort()而不是main()之前?

You write a function prototype so that the compiler knows that function exists, and can use it. 您编写一个函数原型,以便编译器知道该函数存在,并可以使用它。 swap() is used inside qsort() , so it must appear before the line it is used. swap()qsort() ,因此它必须出现在使用它的行之前。 In this case, the swap() prototype is declared inside the qsort() function, but it could as well be declared before the function itself. 在这种情况下, swap()原型在qsort()函数内声明,但也可以在函数本身之前声明。 Or you could define swap() before qsort() and remove the prototype. 或者你可以在qsort()之前定义swap() qsort()并删除原型。

The prototype should be added before the actual function is used for first time. 应该在第一次使用实际功能之前添加原型。 In this case, I do not think its a general practice to have prototype in qsort() function, however, it still serves the purpose. 在这种情况下,我认为在qsort()函数中使用原型并不是一般的做法,但是,它仍然可以达到目的。 The prototype for swap() could also be added before main() too, don't think it will make a difference. swap()的原型也可以在main()之前添加,不要认为它会产生影响。

将函数原型放置在其他函数的定义中通过限制对原型出现的函数的正确函数调用来强制执行最小特权原则。

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

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