普通函数与静态函数

普通函数

普通函数为没有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];
}

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值