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开发者_C百科){
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()?
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.
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.
Placing function prototypes in the definitions of other functions enforces the principle of least privilege by restricting proper function calls to the functions in which the prototypes appear.
精彩评论