c++ - unexpected not all control paths return a value?
问题描述
I am currently writing a program in C++ and have created a function called parseText. When i run this function i get the warning "Not all control paths return a value" however after looking at this code multiple times i cannot find out why this is happening. Is this an incorrect error or have i missed something.
int parseText(std::string line, std::string *posResponses) {
for (int x = 0; x < line.length(); x++) {
line.at(x) = toupper(line.at(x));
}
if (line == "HELP") {
runHelp(3);
return 0; //returns 0 if user entered invalid response and needs to repeat the code
}else if (line == "QUIT") {
return 2; //returns 2 if user wants to quit
}
if (posResponses->size() == 1 && posResponses[0] == line) {
return 1; //returns 1 if there was a valid response
}else if (posResponses[0] == "int") {
int x = posResponses[1].size();
for (int i = 0; i <= x; i++) {
if (posResponses[1].at(i) < 48 || posResponses[1].at(i) > 57) {
return 0; //returns 0 if user entered invalid response and needs to repeat the code
}
return 1; //returns 1 if there was a valid response
}
}
else{
int x = posResponses->size();
for (int i = 0; i <= x; i++) {
if (posResponses[i] == line) {
return 1; //returns 1 if there was a valid response
}
}
return 0; //returns 0 if user entered invalid response and needs to repeat the code
}
}
解决方案
在这个if
分支
} else if (posResponses[0] == "int") {
int x = posResponses[1].size();
for (int i = 0; i <= x; i++) {
if (posResponses[1].at(i) < 48 || posResponses[1].at(i) > 57) {
return 0; //returns 0 if user entered invalid response and needs to repeat the code
}
return 1; //returns 1 if there was a valid response
}
}
如果x
被赋值< 0
,则for
根本不会进入循环,那么return
这个分支就没有语句。
也许您确定x
在运行时不会减去,但编译器必须在编译时确认所有分支。
我不确定你的意图,你可能想要
} else if (posResponses[0] == "int") {
if (posResponses[1].size() == 0 || posResponses[1].at(0) < 48 || posResponses[1].at(0) > 57) {
return 0; //returns 0 if user entered invalid response and needs to repeat the code
}
return 1; //returns 1 if there was a valid response
}
推荐阅读
- r - 将数字从 R 保存到 excel
- r - 在R中的外部迭代后开始嵌套for循环
- c++ - 在cython代码的测试中,使用ctypes是否有效?
- tensorflow - 在计算每行张量值的连续熵时获取 inf
- python - 无法使用 lambda 将参数传递给 pyqtslot
- go - 如何以特定模式生成 UUID
- influxdb - InfluxDB 中有多少标签是最优的
- compiler-construction - 我的指令如何知道操作数堆栈上的地址指向什么?
- multithreading - 如何将多个线程函数结果存储到一个数组或向量中
- javascript - 大于运算符不使用 if 语句