Return type deduction in recursive function

送分小仙女□ 提交于 2020-01-21 04:36:07

问题


Following code compiles :

auto foo(int i) {
  if( i == 1 )
    return i;
  else 
    return foo(i-1)+i ; 
}

While following doesn't, c++1y

auto foo(int i) {
  return (i == 1) ? i : foo(i-1)+i ;  
}

Why can't compiler deduce the return type in second case ? Am I missing something over here ?

I know there's a sequence point after (i == 1) in second scenario, but that shouldn't be affecting compilation, right ?


回答1:


The first works because of this rule, 7.1.6.4/11 of the latest draft

Once a return statement has been seen in a function, however, the return type deduced from that statement can be used in the rest of the function, including in other return statements.

So the return type is deduced as int from the first return statement; the second is just checked to make sure that it also gives int, assuming that the recursive call does.

The second doesn't compile because the type of the expression depends on the return type; so the type can't be deduced.




回答2:


A recursive function can have an auto return type only if it has a non-recursive return statement before the recursive call. See Return type deduction for normal functions.



来源:https://stackoverflow.com/questions/22040875/return-type-deduction-in-recursive-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!