当我尝试使用以下代码编译代码时:g++ -Wall -std=c++11 -o test10 program10.cpp
发生这种情况:
program10.cpp: In function 'int getInt(std::string)':
program10.cpp:76:1: warning: control reaches end of non-void function [-Wreturn-type]
以下是代码:
int getInt(string str) {
string bin[] = {"11000", "00011", "00101", "00110", "01001",
"01010", "01100", "10001", "10010", "10100"};
for (int i = 0; i < 10; i++) {
if (str.compare(bin[i]) == 0) {
return i;
}
}
}
答案 0 :(得分:0)
如果数组中没有任何字符串与函数的参数字符串匹配,那么即使函数返回int,函数也不会返回任何内容。我建议返回类似-1的函数作为函数的最后一个语句,以指示何时发生这种情况。
答案 1 :(得分:0)
编译器简明扼要地解释了您的警告。只有找到+---+--------+----------+--+-----+------------------------------------------------+-----------------------+-----+--------------------------------+------+--------+----------------------------------------------+
| 1 | SIMPLE | invoices | | ref | Invoice_CompanyID_idx,invoices_UserID___Active | Invoice_CompanyID_idx | 144 | const | 7750 | 10.00 | Using where; Using temporary; Using filesort |
| 1 | SIMPLE | users | | ref | users_UserID_Deleted | users_UserID_Deleted | 148 | sterling.invoices.UserID,const | 1 | 100.00 | |
+---+--------+----------+--+-----+------------------------------------------------+-----------------------+-----+--------------------------------+------+--------+----------------------------------------------+
数组中的一个字符串时,代码才会到达return
语句。这是您应该选择单个退出点的众多原因之一(提高可读性,赢得此警告,并且更容易调试)。您还应该更喜欢传递非POD类型作为函数参数的参考。
bin