为什么我们需要功能上的原型? [英] Why do we need prototype in function?

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

问题描述

我正在学习C,我的书正在解释如何原型化一个函数",以便我们在定义它之前就可以使用它.

I'm studying C and my book is explaining how to "prototype a function" so we can use it before we define it.

关键是我无法想象在定义一个函数之前需要使用一个函数的情况,为什么我们不能一开始就定义它呢?

The point is that I can't imagine a situation in which is needed to use a function before have defined it, why can't we just define it at the beginning?

能否请您提供一个示例,其中严格要求对函数进行原型制作(如果存在)?

Can you please provide an example in which is strictly necessary to prototype a function (if it exists)?

推荐答案

请考虑以下程序:

#include <stdio.h>

void add(int, int);

int main() {
    add(5, 3);
    return 0;
}

void add(int a, int b) {
    printf("%d", a+b);
}

在这里,当您从 main()调用 add(5,3)时,编译器会知道 add()是什么-多亏了第3行中的语句 void add(int,int),它需要的参数和返回类型.如果注释掉了该语句,则编译器将不知道 add()是,并且会给您一个错误.因此,第3行告诉编译器您以后定义了函数 add(),这使其完全可以在 main()中使用.或者,如果您在之前 main()之前编写 add()函数,则编译器会知道 add()是当您调用它时;因此在这种情况下不需要功能原型.

Here, when you call add(5, 3) from main(), the compiler knows what add() is - the parameters it takes and the return type, thanks to the statement void add(int, int) in line 3. If this statement is commented out, then the compiler won't know what add() is and would give you an error. Thus, line 3 tells the compiler that you have defined the function add() later, which makes it perfectly eligible to be used in main(). Alternately, if you write the add() function before main(), then the compiler knows what add() is when you call it; so a function prototype is not required in this case.

希望这很有用.

这篇关于为什么我们需要功能上的原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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