How does the implicit return of 0 tie into the deduction of the main return?
N3936 [basic.start.main]
2
The implementation does not have to predefine the functionmain
. This function should not be overloaded. It must have a declared return typeint
, but otherwise its type is implementation-defined. the implementation should provide both- a function
()
that returnsint
and- function (
int
, pointer to pointer tochar
), returningint
5
The return statement inmain
has the effect of exiting the main function (destroying any objects with automatic storage time) and callingstd::exit
with the return value as an argument. If control reaches the end of the main one without encountering a return statement, the effect is to execute
return 0;
DR 1669 added the word declared to the wording, implying that if main
there were to be declared auto
, a back return type was needed. However, the wording provided by DR 1003 says, as in the quote above, that "an implementation should allow as a function ... return int
..." This wording is much less strict when it comes to what the expression should look like main
.
So, subject to the rules auto
, this is implicit return 0;
enough to do
auto main() { }
legal?
source to share
Seems like it is auto main() { }
not legal in C ++ 14.
[dcl.spec.auto]
2
A placeholder type can appear with a function declaration in decl-specifier-seq, type-specifier-seq, transform-function-id, or trailing-return-type, in any context where such a declarator is valid. Where the function declarator includes a return type (8.3.5) that specifies the declared return type of the function. If the declared return type of a function contains a placeholder type, the return type of the function is inferred from the statementsreturn
to the body of the function, if any.
10
If a function with a declared return type using a placeholder type has no operatorsreturn
, the typereturn
is inferred as though from a return statement without an operand in the closing parenthesis of the function body. [Example:
auto f() { } // OK, return type is void auto* g() { } // error, cannot deduce auto* from void()
- end of example]
This apparently means that since there are no operators return
, it main()
is outputted as void
, and therefore the program is poorly formed. However, it leaves the ambiguity open, which seems to allow implicit inference return 0
on int
. Oh good.
source to share