kmi*_*las -9 c++ int return void c++11
有什么理由我们需要无效功能吗?
出于与int main()
标准相同的原因,为什么不简单地0
从不需要返回值的函数返回?我看到使用int
类型有三个直接的好处:
1.我们可以返回一个代码来指示函数状态; 通常,如果出现问题,我们可以返回非零错误代码.
2.我们可以在调试时输出函数的返回值
3.它是main()例程的标准; 就是,int main() {}
.为什么不跟风呢?
是否有任何理由为什么我们宁愿void
过int
?
示例:对奶酪数组进行排序并通过引用返回的函数.
#include <iostream>
#include <string.h>
int sortArrayInt(string & _cheese[]) { // pun intended ;D
int errCode = 0;
try {
// ..sort cheese[] array
} catch(e) {
errCode = 1;
}
return errCode;
}
void sortArrayVoid(string & _cheese[]) {
// .. sort cheese[] array
// no return code to work with, doesn't follow int main() standard, and nothing to output.
}
int main() {
string cheese[5] = {"colby","swiss","cheddar","gouda","brie"};
std::cout << "Sort Status: " << sortCheeseArrayInt(cheese) << std::endl;
sortArrayVoid(cheese);
// ..print cheese array
}
OUTPUT:
Sort Status: 0
brie, cheddar, colby, gouda, swiss
Run Code Online (Sandbox Code Playgroud)
Ser*_*eyA 10
当函数业务逻辑不需要时,没有理由返回整数.不这样做的原因如下: