简体   繁体   中英

Why is the function prototype inside a different function block?

I am trying to understand C, by going through 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. It compiled fine and ran fine. My question is, why is the prototype for swap() put in the function qsort() and not before 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. In this case, the swap() prototype is declared inside the qsort() function, but it could as well be declared before the function itself. Or you could define swap() before qsort() and remove the prototype.

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. The prototype for swap() could also be added before main() too, don't think it will make a difference.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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