函数的作用:
- 提高代码的复用率
- 提高程序的模块化组织
函数分类
系统函数 (库函数)
- 标准 C 库,libc
- 作用
- 引入头文件 — 声明函数
- 根据函数原型调用
用户自定义函数
- 除了提供函数原型外,还需要提供函数调用
函数的定义、声明和调用
函数定义
- 函数原型
- 返回值类型 函数名(形参列表)
- 函数体
- 大括号一对 {具体代码实现}
函数声明
函数声明一般写在 .h 头文件中。
- 包含
- 函数原型 + 分号(;)
- 隐式声明
- 返回值都是 int,根据调用语句补全函数名和形参列表。例如,int 函数名();
- 不要依赖隐式声明
函数调用
- 函数名 (实参列表)
- 在调用时,传参必须严格按照形参填充 (参数的个数、类型、顺序)
- 退出程序
- return
- 返回当前函数的调用,将返回值返回给调用者
- exit()
- 退出当前程序
- 在 main 函数中调用 exit(),结果和 return 一样;在子函数中调用 exit(),则程序终止
- return
示例
- 简单加法
#define _CRT_SECURE_NO_WARNINGS #include #include int add(int a, int b) { return a + b; } int main(void) { int c; c = add(10, 20); printf("%d\n", c); system("pause"); return 0; }
- 冒泡算法使用函数封装
#define _CRT_SECURE_NO_WARNINGS #include #include // 冒泡算法函数 void buble_sort(int str[], int n) { int temp; for (size_t i = 0; i < n - 1; i++) { for (size_t j = 0; j str[j + 1]) { temp = str[j]; str[j] = str[j + 1]; str[j + 1] = temp; } } } } int main(void) { int str[6] = {1, 2, 6, 4, 5, 3}; int n = sizeof(str) / sizeof(str[0]); buble_sort(str, n); // 函数调用 for (size_t k = 0; k < n; k++) { printf("%d ", str[k]); } putchar('\n'); system("pause"); return 0; }
多文件编程
多文件编程就是将多个含有不同功能的 .c 文件模块,编译到一起,生成一个可执行文件。
引入头文件
#include <系统头文件>
#include "用户自定义头文件"
- 示例
#pragma once // include 头文件 #include "head.h" #include #include #include #include #include // 函数声明 int add(int a, int b); int sub(int a, int b); // 类型定义 // 宏定义 #define N 6 #define PI 3.14
- gcc 编译多个文件
gcc a01.c a02.c a03.c -o app.exe
防止头文件重复包含 (头文件守卫)
//#pragma once // Windows 中的方法
#ifndef __HEAD_H__ // ifndef 表示 if no define
#define __HEAD_H__
头文件内容
#endif