c++ - 带有 if 语句的函数没有返回值
问题描述
如果不满足条件,如何从函数返回。我正在尝试创建一个除法函数,它将返回除以 2 个数字的结果,但如果将其除以零,我该如何返回任何内容。
int div(int n1, int n2)
{
if (n2 > 0)
{
return n1 / n2;
}
}
编译时收到此警告:
警告:控制到达非无效函数的结尾
我明白这意味着什么,但是如果我不想返回值,我应该在 n2 为 0 的情况下输入什么;
解决方案
如果一个函数有返回类型,它必须返回something。因此,您可以:
返回函数和调用者同意表示“非值”的标记值,例如:
int div(int n1, int n2)
{
if (n2 != 0)
{
return n1 / n2;
}
else
{
return -1; // or whatever makes sense for your use-case...
}
}
如果没有可以使用的标记值,则可以使用std::optional
(仅限 C++17 及更高版本),例如:
#include <optional>
std::optional<int> div(int n1, int n2)
{
if (n2 != 0)
{
return n1 / n2;
}
else
{
return std::nullopt;
}
}
或者,您可以更改函数以使用输出参数和bool
返回值,例如:
bool div(int n1, int n2, int &result)
{
if (n2 != 0)
{
result = n1 / n2;
return true;
}
else
{
return false;
}
}
否则,您将只需要throw
一个例外,例如:
#include <stdexcept>
int div(int n1, int n2)
{
if (n2 == 0)
{
throw std::invalid_argument("n2 must not be 0");
}
return n1 / n2;
}
推荐阅读
- javascript - 如何在 ionic 中使用 jQuery 日期时间范围选择器
- .net - 通过 BotFramework 获取电报中的电话号码
- python - 如果变量不是 None 并且大于一行中的某个值,如何检查 python?
- linux - 如果路径不存在,请尝试其他路径
- python - “from .checks import *”和“from .import 检查”之间的区别
- cryptography - 我正在尝试解决 RSA 算法,我如何生成公钥?在数学问题中......我无法理解
- javascript - 如何在js中选择时将数据存储在内存中
- ios - 在使用 swift ios 的某些 URL 情况下,Alamofire 进度状态显示 0.0
- php - Mysql慢查询日志,有没有办法启用哪个php脚本执行查询?
- python - 当你有 2 个 Python 版本时如何使用 pip 安装包