1 链接
2 Why funcitons
- 模块化编程
- 代码复用
Struct Matrix//
{
int rows;
int cols;
float * pData;
}
现在写个程序来找到矩阵中的最大值
Matrix matA;
float maxa = FLT_MIN;
for (int r = 0; r < matA.rows; r++)
for(int c = 0; c < matA.cols; c++)
{
float val = matA.pData[r * matA.cols + c];
maxa = (maxa > val ? maxa : val);
}
多个矩阵都想查询
- 最简单的方法是拷贝赋值代码,然后修改变量名称
- 容易改错
- 维护困难<万一需要修改查找逻辑>
- 解决方案
- 使用函数
3 函数的定义
float matrix_max(Struct Matrix max)
{
float maxa = FLT_MIN;
for (int r = 0; r < matA.rows; r++)
for(int c = 0; c < matA.cols; c++)
{
float val = matA.pData[r * matA.cols + c];
maxa = (maxa > val ? maxa : val);
}
return maxa;
}
4 函数的调用方法
float maxa = matric_max(matA);
需要对函数的输入需要进行检查,
- 检查matA.pData是不是NULL
- 检查行列数是否合理
?思考:
怎么通知调用的函数函数出了问题
- 返回值貌似不行
5 函数放在哪
5.1 被调用函数放在调用函数前
5.2 先声明再调用
编译器是从上往下读的。函数被调用前必须要声明。声明里的parameter可以省略,但必须有参数类型。
5.3 函数的声明放到一个头文件中
关于#ifndef DRAW_H #define DRAW_H #endif的几点说明
- 此宏定义的名字可以指定,一般跟头文件有关
- 次宏定义的作用的防止函数重定义错误
6 函数是怎么运行的
call return
函数运行是有代价的
7 conclusion
从为什么使用函数入手,讲解了怎么定义函数,怎么调用函数以及怎么组织函数,到最后讲了函数的运行做了哪些事情。期待下一期。