Return type deduction in recursive function

前端 未结 2 1290
甜味超标
甜味超标 2021-01-05 06:01

Following code compiles :

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

While following doesn\'t,

2条回答
  •  别那么骄傲
    2021-01-05 06:42

    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.

提交回复
热议问题