- Statement
return;
is only valid if the function return type isvoid
. - Just finish the execution of the function, no value returned.
如果函数的返回值类型为void,就不需要返回具体的返回值,直接结束即可。
| ```cpp void print_gender(bool isMale) { if(isMale) cout << “Male” << endl; else cout << “Female” << endl; return; }
| ```cpp
void print_gender(bool isMale)
{
if(isMale)
cout << "Male" << endl;
else
cout << "Female" << endl;
}
| | —- | —- |
- The return type can be a
fundamental
type or acompound
type.- 既可以是基本数据类型,也可以是组合数据类型
- 返回值的方式是:Pass by
value
:- Fundamental types: the value of a constant/variable is copied
- Pointers: the address is copied
- Structures: the whole structure is copied
```cpp Matrix create_matrix(int rows, int cols) { Matrix p = new Matrix{rows, cols}; p->pData = new float[p->rows * p->cols]{1.f, 2.f, 3.f}; // you should check if the memory is allocated successfully // and don’t forget to release the memory return p; }float maxa = matrix_max(matA); Matrix * pMat = create_matrix(4,5);
- If we have a lot to return,Such as a matrix addition function (A+B->C)
- 如果有很多内容需要返回
- A suggested prototype:
- To use `references` to avoid data copying
- To use `const` parameters to avoid the input data is modified
- To use non-const reference parameters to receive the output
```cpp
bool matrix_add(const Matrix & matA, const Matrix & matB, Matrix & matC)
{
// 1. check the dimensions of the three matrices
// 2. re-create matC if needed
// 3. do: matC = matA + matB
// 4. return true if everything is right
}