模块化编程和函数原型

Modular programming and functions prototypes

我正在这个(法语)网站上学习 C:http://openclassrooms.com/courses/apprenez-a-programmer-en-c 我在模块化编程的章节中说:

Because the order has real importance here: if you put your function before the main in your source code, your computer has read it and knows it. When you will make a call to the function the computer will know the function and know where to go get it.

However, if you put your function after the main, it will not work because the computer does not know the function yet. Try it and see!

我尝试将我的函数放在主函数之后,如下面的代码所示,但我的代码有效:

#include <stdio.h>
#include <stdlib.h>
 
int main(int argc, char *argv[])
{
    int nbE = 0;
    int nbM = 0;
    printf("Nombre a tripler : ");
    scanf("%d", &nbE);
    nbM = triple(nbE);
    printf("Le nombre triple de %d est %d", nbE, nbM);
 
    return 0;
}
 
int triple(int nb)
{
    return nb * 3;
}

你能解释一下它为什么起作用吗?

您的代码可能是根据旧的 C 标准编译的,该标准不需要原型。相反,它假定它看到的任何未声明的函数都接受它传递的任何参数,并且 returns int.

如果您使用警告选项 (-Wall) 进行编译,您应该始终这样做,那么您将看到编译器通过创建隐式 猜测 函数的存在声明。

通常您不希望编译器猜测您的函数声明,因为它可能会弄错它们。保持安全并始终提前声明您的功能。

这是因为编译器假定参数和 return 值是 int,它们是。如果您的函数 return 编辑了 float 值,它将无法正常工作。这就是使用函数原型的原因:声明函数(比如在头文件中),以便在构建此模块的编译器看不到主体的情况下可以正确使用它。正文可能在另一个文件中,或者在库中。所以你应该

#include <stdio.h>
#include <stdlib.h>

int triple(int nb);      // <-- function prototype

int main(int argc, char *argv[]) { ...

在程序的顶部。但是没必要把整个函数放在main.

之前

程序不包含函数原型声明。 . 应该有一个:

int triple(int);