Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will automatic return type deduction work for main?

Tags:

c++

c++14

Will I be able to do the following for the main function in C++1y (C++14):

auto main() {     // ... } 

So will the return type automatically be int even though we don't need to use an explicit return 0;?

like image 786
template boy Avatar asked Jun 16 '13 15:06

template boy


People also ask

What is automatic type deduction?

With auto type deduction enabled, you no longer need to specify a type while declaring a variable. Instead, the compiler deduces the type of an auto variable from the type of its initializer expression.

Can you use auto as a return type in C++?

In C++14, you can just use auto as a return type.

Can a function have an auto return type?

Using auto to deduce the return type of a function in C++11 is way too verbose. First, you have to use the so-called trailing return type and second, you have to specify the return type in a decltype expression.

Which C++ added feature of Auto for return type of function?

C++: “auto” return type deduction The “auto” keyword used to say the compiler: “The return type of this function is declared at the end”. In C++14, the compiler deduces the return type of the methods that have “auto” as return type.


1 Answers

No, it won't be allowed. Paragraph 7.1.6.4/10 of the C++14 Standard Draft N3690 specifies:

If a function with a declared return type that uses a placeholder type has no return statements, the return type is deduced as though from a return statement with no operand at the closing brace of the function body. [...]

This means that omitting a return statement in main() would make its type void.

The special rule introduced by paragraph 3.6.1/5 about flowing off the end of main() specifies:

[...] If control reaches the end of main without encountering a return statement, the effect is that of executing

return 0; 

The wording says that the "effect" during the execution of the program is the same as though a return 0 was present, not that a return statement will be added to the program (which would affect type deduction according to the quoted paragraph).

EDIT:

There is a Defect Report for this (courtesy of Johannes Schaub):

Proposed resolution (November, 2013):

Change 3.6.1 [basic.start.main] paragraph 2 as follows:

An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a declared return type of type int, but otherwise its type is implementation-defined. All implementations An implementation shall allow both

  • a function of () returning int and
  • a function of (int, pointer to pointer to char) returning int

as the type...

like image 70
Andy Prowl Avatar answered Oct 18 '22 00:10

Andy Prowl