Take the 2-minute tour ×

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)


last = left;

    if (v[i]<v[left])
        swap(v,++last, i);



    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()?

share|improve this question
It can be done both ways. I suppose this is done to put the prototype in a scope, not that it matters. –  Stefan Dragnev Feb 17 '11 at 13:48

2 Answers 2

up vote 4 down vote accepted

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.

share|improve this answer
This is incorrect. The prototype for swap() could not be added in main(), as it must be declared before it's used in qsort(). It is a strange place to put the prototype, but the only other place it could be legally put would be before swap(). –  Bradley Swain Feb 17 '11 at 14:54
@Bradley - Edited my answer. –  Sachin Shanbhag Feb 17 '11 at 14:57

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.

share|improve this answer

Your Answer


