Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't auto be return type of a function? [duplicate]

Tags:

c++

c++11

auto

My question is, why can't the return type of a function be deduced ? , or more simply why the following code gives error :

auto myfunc(int a)
{
int a = 12;
return a;
}

Why this isn't valid ?

like image 936
Anthony Avatar asked Sep 29 '22 02:09

Anthony


2 Answers

It is a feature in C++14 , You can try it with GCC 4.9 or clang by setting the -std=c++1y flag.

Live Example : http://coliru.stacked-crooked.com/a/00b8b708d6f0f45b

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3638.html

like image 200
Abhishek Gupta Avatar answered Oct 05 '22 06:10

Abhishek Gupta


It is allowed in C++14 (and is called automatic return type deduction), you may enable it in your compiler with std=c++1y for now.

You can use the trailing return type if your compiler supports c++11 but not c++14 :

auto myfunc(int a) -> int
{
int b = a;
return a;
}
like image 41
quantdev Avatar answered Oct 05 '22 07:10

quantdev