美文网首页C语言
普通函数与静态函数

普通函数与静态函数

作者: 风情云 | 来源:发表于2020-03-26 22:26 被阅读0次

    普通函数

    普通函数为没有static关键字修饰的函数:

    //普通函数
    int sub(int a, int b)
    {
        return a - b;
    }
    

    普通函数可以跨文件使用,调用普通函数需要经过压栈与弹栈的过程。且在其他文件不允许起同名函数。

    静态函数

    //静态函数
    static int mulpti(int a, int b)
    {
        return a * b;
    }
    

    定义静态函数:static 返回值类型 函数名(形参列表)
    静态函数不可以跨文件使用,调用静态函数没有压栈,弹栈这些开销,效率会比较高。在其他文件允许使用同名函数。

    多文件下使用静态函数

    test.h

    static int add(int a, int b);
    

    test.c

    static int add(int a, int b)
    {
        return a + b;
    }
    

    main.c

    #include"test.h"
    int main()
    {
        add(1,2);
        return 0;
    }
    

    编译器报错,为定义该函数。尝试下面的写法:

    test.h

    static int add(int a, int b)
    {
        return a + b;
    }
    

    main.c

    #include"test.h"
    int main()
    {
        add(1,2);
        return 0;
    }
    

    将静态函数写在.h文件中,编译通过。静态函数的用法一般在黑盒设计,用户只能使用模块给定的接口,完成任务,不需要知道里面的细节。
    test.h

    #include<stdio.h>
    #define IDNUM 100
    #define NAMENUM 100
    const char *look_upname(const char *str);
    

    test.c

    static int id[IDNUM];
    static char *name[NAMENUM];
    //静态函数,只能内部使用
    static int find_name(const char *str)
    {
        if(name == NULL) return -1;
        int i = 0;
        for(; *name[i] != *str && i < NAMENUM; i++);
        if(i == NAMENUM) return -2;
        return i;
    }
    //对外接口,供外部使用
    const char *look_upname(const char *str)
    {
        int ret = find_name(str);
        if(ret < 0) return NULL;
        return id[ret];
    }
    

    如上所示,只有一个对外接口,输入名字查学号,并不清楚里面如何实现。使用者只需使用提供的外部接口,内部是如何处理的不需要知道,也无权知道,这就是黑盒设计。保护里面的数据不被篡改,静态函数做辅助函数完成外部接口。


    微信号

    相关文章

      网友评论

        本文标题:普通函数与静态函数

        本文链接:https://www.haomeiwen.com/subject/xtnhuhtx.html