控制可能会达到非void函数错误结束if语句

我得到的错误控制可能会达到此代码的非无效function的结束:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (changeData.selectedSegmentIndex == 0) { return self.tweets.count; } else if (changeData.selectedSegmentIndex == 1) { return self.tweets1.count; } else if (changeData.selectedSegmentIndex == 2) { return self.tweets2.count; } } 

为什么?

因为当你所有的条件都失败时,你不会从函数中返回任何东西。

在一个函数中多重返回语句也不是一个好习惯。

这样做:

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { int count = 0; if (changeData.selectedSegmentIndex == 0) { count = self.tweets.count; } elset if (changeData.selectedSegmentIndex == 1) { count = self.tweets1.count; } else if (changeData.selectedSegmentIndex == 2) { count = self.tweets2.count; } return count; } 

Midhun MP有你的答案和更好的代码风格。 我强烈build议用switch语句replace所有嵌套的else if,以及你真的不想要别的ifs,如果你可以避免它们…

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ NSInteger count = 0; switch (changeData.selectedSegmentIndex) { case 0: count = self.tweets.count; break; case 1: count = self.tweets1.count; break; case 2: count = self.tweets2.count; break; default: break; } return count; } 

如果你认为它可以禁用它:

在这里输入图像说明

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSInteger count = 0; if (changeData.selectedSegmentIndex == 0) { count = self.tweets.count; } else if (changeData.selectedSegmentIndex == 1) { count = self.tweets1.count; } else { count = self.tweets2.count; } return count; } 

要么

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSInteger count = 0; if (changeData.selectedSegmentIndex == 0) { count = self.tweets.count; } else if (changeData.selectedSegmentIndex == 1) { count = self.tweets1.count; } else if (changeData.selectedSegmentIndex == 2){ count = self.tweets2.count; } return count; } 

虽然我同意大多数回答build议避免在一般情况下的多个return ,有时多次return是好的和有用的。 例如调度一个enum

 #include <iostream> #include <string> enum direction { north, east, south, west }; std::string to_string(direction d) { switch (d) { #define CASE(C) case C: return #C CASE(north); CASE(east); CASE(south); CASE(west); #undef CASE } } int main() { std::cout << to_string(west) << '\n'; } 

如果你使用GCC进行编译,你会得到(C或C ++,它是一样的):

 $ g++-4.9 -Wall foo.cc foo.cc: In function 'std::string to_string(direction)': foo.cc:17:1: warning: control reaches end of non-void function [-Wreturn-type] } ^ 

铿锵不抱怨。 哪个不太好,实际上,因为它也编译这个没有警告:

 int main() { std::cout << to_string(direction(666)) << '\n'; } 

这导致:

 $ clang++-3.5 -Wall foo.cc $ ./a.out zsh: illegal hardware instruction ./a.out 

所以人们必须“打”海湾合作委员会的警告。 一个错误的做法是增加发言权

 default: abort(); 

switch 。 当然,它可以治愈症状,但现在GCC不会再抱怨,如果我添加一个新的direction ,说zenith ,但忘记覆盖to_string 。 所以,真的, 切换使用枚举时不要使用默认情况

然后你可以在switch 留下一个abort (这是笨拙的,而不使用内部return )。