为什么函数原型在不同的函数块中? [英] Why is the function prototype inside a different function block?

查看:50
本文介绍了为什么函数原型在不同的函数块中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过 K&R 来理解 C.我无法理解书中两个函数的这段代码:

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;
}

这两个函数对给定的数组执行快速排序.在主函数中,我创建了一个 int 数组并调用了 qsort.它编译得很好并且运行得很好.我的问题是,为什么 swap() 的 prototype 放在函数 qsort() 中而不是放在 main() 之前?

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

推荐答案

原型应该在第一次使用实际功能之前添加.在这种情况下,我不认为在 qsort() 函数中有原型是一种普遍的做法,但是,它仍然可以达到目的.swap() 的原型也可以加在 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.

这篇关于为什么函数原型在不同的函数块中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆