首页 > 编程笔记 > C语言笔记 阅读:3

C语言函数的声明(通俗易懂,附带实例)

分析一个示例,isTriangle() 和 areaOfTriangle() 的函数定义放到了 main() 函数调用后:
#include <stdio.h>
#include <math.h>

int main()
{
    double a, b, c;
    scanf("%lf %lf %lf", &a, &b, &c);
    if(isTriangle(a, b, c) == 0)
    {
        printf("Not a triangle\n");
        return 0;
    }
    double s;
    s = areaOfTriangle(a, b, c);
    printf("area of triangle is %f", s);
    return 0;
}

// 函数定义被放到了函数调用后
double areaOfTriangle(double a, double b, double c)
{
    double p, s;
    p = (a + b + c) / 2;
    s = sqrt(p * (p - a) * (p - b) * (p - c));
    return s;
}

int isTriangle(double a, double b, double c)
{
    if (a + b > c && a + c > b && b + c > a)
    {
        return 1;
    }
    return 0;
}
然而,我们在编译代码时发现编译器无法识别 areaOfTriangle() 和 isTriangle() 两个函数,如下图所示:


图 1 找不到标识符

原因是编译器在调用这两个函数前没有读到任何有关它们的声明。因此,我们需要在函数被调用前进行函数声明。

在 C语言中,函数声明的作用是提供函数的返回类型、函数名和参数类型,以便编译器在编译时知道如何调用这个函数。函数声明的写法非常简单:函数头+分号。

例如,我们可以在程序开头添加如下函数声明:
double areaOfTriangle(double a, double b, double c);
int isTriangle(double a, double b, double c);
这样,编译器在编译代码时就能够识别这两个函数,并且知道它们是什么类型的函数以及如何调用它们。

总结,函数声明是在函数被调用之前提供函数接口信息的方式。在一个源文件中,如果在调用函数前没有函数定义,则可以使用函数声明通知编译器该函数存在。函数声明的写法是函数头+分号

我们对文章开头的示例进行修改,加上函数声明:
#include <stdio.h>
#include <math.h>
//函数调用前加上了函数声明,告诉编译器该函数存在
double areaOfTriangle(double a, double b, double c);
int isTriangle(double a, double b, double c);

int main()
{
    double a, b, c;
    scanf("%lf %lf %lf", &a, &b, &c);
    if(isTriangle(a, b, c) == 0)
    {
        printf("Not a triangle\n");
        return 0;
    }
    double s;
    s = areaOfTriangle(a, b, c);
    printf("area of triangle is %f", s);
    return 0;
}

// 函数定义被放到了函数调用后
double areaOfTriangle(double a, double b, double c)
{
    double p, s;
    p = (a + b + c) / 2;
    s = sqrt(p * (p - a) * (p - b) * (p - c));
    return s;
}

int isTriangle(double a, double b, double c)
{
    if (a + b > c && a + c > b && b + c > a)
    {
        return 1;
    }
    return 0;
}
在程序中,我们添加了函数声明,这样编译器在调用函数时就可以知道函数的参数类型和返回值类型。当调用函数时,编译器还会检查参数类型和数量是否正确,并检查返回值是否被正确处理。

值得注意的是,函数声明可以省略参数变量名。这是因为在声明函数时,参数的名字并不重要,重要的是参数的类型和数量。因此,即使函数声明和定义中的参数变量名不同也是可以的。

例如,下面的写法都是正确的:
//  省略参数变量名
double areaOfTriangle(double, double, double);
int isTriangle(double, double, double);
//  乱写参数变量名
double areaOfTriangle(double xsie, double sgrb, double xvdc);
int isTriangle(double aooj, double bngb, double vfhfc);

相关文章