“cpp[警告] 控制到达非void函数的末尾”解决方案

本文最后更新于:2021年5月9日 晚上

#“cpp[警告] 控制到达非void函数的末尾”解决方案

在用C++写Leetcode1006笨阶乘那题时遇到的问题,devcpp是可以正常运行给出答案但编译器给出了警告,而且leetcode上编译错误,报错信息如下:

image-20210509192545128

错误的代码如下:

int clumsy_error(int N) {
	std::map<int, int> um = {{ 1, 1 }, { 2, 2 }, { 3, 6 }, {4, 7} };
	if (N <= 4) {
		return um[N];
	}
	if (N > 4) {
		int t = N % 4;
		int res = static_cast<double>(N * (N - 1) / (N - 2));
		if (t == 0) {
			return res;
		} else if (t == 3) {
			return res - 2;
		} else {
			return res + 1;
		}
	}
}

原始代码我忘了,反正逻辑上看这个除了比较傻逼以外没大问题,但就是会warning,而且leetcode就是不给过。

解决方案

在网上搜了下了解到它大概意思是:非空返回值(非void)的函数必须要有返回值,而我写的函数里仅在满足某些条件时才返回值。

也就是说,我在 if 语句里给定的范围漏了返回值,if有些分支没有返回值就不给过!每个地方都要有值return回来。

把else写进去代替之前那个范围之后就OK了

int clumsy_correct(int N) {
	std::map<int, int> um = {{ 1, 1 }, { 2, 2 }, { 3, 6 }, {4, 7} };
	if (N <= 4) {
		return um[N];
	} else {
		int t = N % 4;
		int res = static_cast<double>(N * (N - 1) / (N - 2));
		if (t == 0) {
			return res;
		} else if (t == 3) {
			return res - 2;
		} else {
			return res + 1;
		}
	}
}