Control may reach end of non-void function error if-statement

后端 未结 5 405
[愿得一人]
[愿得一人] 2021-01-20 06:48

I\'m getting the error Control may reach end of non-void function on this code:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInte         


        
5条回答
  •  猫巷女王i
    2021-01-20 07:52

    While I agree with most answers that suggest to avoid multiple returns in the general, on occasions multiple returns 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 returns).

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题