Why is a function prototype located inside another function block?

I am trying to understand C by going through K & R. I find it difficult to understand this code for the 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 functions perform quicksort for the given array. In the main function, I created an int array and called qsort. It is configured and works great. My question is why the prototype for swap () is placed in qsort () function, and not before main ()?

+10
c prototype
source share
3 answers

A prototype must be added before the actual function is used for the first time. In this case, I do not think that its general practice has a prototype in the qsort() function, however it still serves the purpose. The prototype for swap() can also be added before main() , do not think that it will matter.

+5
source share

You write a function prototype so that the compiler knows that the function exists and can use it. swap() used inside qsort() , so it should appear before the line in use. In this case, the prototype swap() declared inside the qsort() function, but it can also be declared before the function itself. Or you can define swap() to qsort() and remove the prototype.

+5
source share

Placing function prototypes in other function definitions ensures that the principle of least privilege is applied, limiting the proper function calls to functions in which prototypes appear.

0
source share

All Articles