I\'m getting the error Control may reach end of non-void function on this code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInte
-
While I agree with most answers that suggest to avoid multiple return
s in the general, on occasions multiple return
s is nice and useful. For instance dispatching on an enum
:
#include
#include
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';
}
If you compile with GCC, you get (C or C++, it's the same):
$ 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]
}
^
Clang does not complain. Which is not so nice, actually, since it also compiles this without warnings:
int main()
{
std::cout << to_string(direction(666)) << '\n';
}
which results in:
$ clang++-3.5 -Wall foo.cc
$ ./a.out
zsh: illegal hardware instruction ./a.out
So one has to "fight" GCC's warning. One wrong approach would be to add say
default: abort();
to the switch
. Sure, it cures the symptom, but now GCC will no longer complain if I add a new direction
, say zenith
, but forget to cover it in to_string
. So really, never use a default case when switching on an enum.
Then you can leave an abort
after the switch
(which is clumsy to do without using inner return
s).
- 热议问题