Return type deduction in recursive function

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 ?

Answers


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.


Need Your Help

Is there a way to list all additions (ever) in a Git project?

git github bitbucket

Sometimes at the end of a project I think to myself "Wow, I just wrote a ton of lines of code for that project." But I never know just how much.

RibbonControl is stretching image

c# wpf xaml .net-4.0

I'm using the Microsoft.Windows.Controls.Ribbon in my WPF application, and it is stretching the RibbonCommand image larger than it is supposed to be. The image is inserted as follows:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.