Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of 'auto func(int)' before deduction of 'auto' in C++14

I have compiled following program in GCC using C++14.

#include <iostream> using namespace std;  auto func(int i);  int main()  {     auto ret = func(5);     return 0; }  auto func(int i)  {   if (i == 1)     return i;                 else     return func(i-1) + i;   } 

But, I get the following error.

In function 'int main()': 8:16: error: use of 'auto func(int)' before deduction of 'auto'  auto ret = func(5); 

So, what am I missing here?

like image 454
msc Avatar asked Apr 20 '17 08:04

msc


People also ask

What does auto function do in c++?

The auto keyword directs the compiler to use the initialization expression of a declared variable, or lambda expression parameter, to deduce its type.

When to use auto in c++?

The auto keyword specifies that the type of the variable that is begin declared will automatically be deduced from its initializer and for functions if their return type is auto then that will be evaluated by return type expression at runtime.

How auto works c++?

The auto keyword in C++ automatically detects and assigns a data type to the variable with which it is used. The compiler analyses the variable's data type by looking at its initialization. It is necessary to initialize the variable when declaring it using the auto keyword.


2 Answers

This is [dcl.spec.auto/11]:

If the type of an entity with an undeduced placeholder type is needed to determine the type of an expression, the program is ill-formed. Once a non-discarded 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. [ Example:

auto n = n;                     // error, n's type is unknown auto f(); void g() { &f; }                // error, f's return type is unknown auto sum(int i) {   if (i == 1)     return i;                   // sum's return type is int   else     return sum(i-1)+i;          // OK, sum's return type has been deduced } 

 — end example ]

To translate this into English: the compiler needs to know the return type before you can use the function. In case of auto used like this, this is typically achieved by moving the definition before the point of use. If you don't actually need to use return type deduction, you can keep the definition after the use if you provide a signature, including the return type, in the declaration.

like image 70
Griwes Avatar answered Sep 20 '22 14:09

Griwes


Clang has a much better error message for that one:

main.cpp:8:16: error: function 'func' with deduced return type cannot be used before it is defined     auto ret = func(5);                ^ 

I guess that's self-explanatory.

like image 44
Bartek Banachewicz Avatar answered Sep 17 '22 14:09

Bartek Banachewicz