I happened to come across the below code snippet in a video on C++11, where the author uses
auto main()->int
I didn't understand this. I tried to compile in g++
using -std=c++11
and it works. Can somebody explain to me what is going on here? I tried to search using "auto main()->int" but didn't find any help.
C++11 introduced a notation for trailing return types: If a function declaration is introduced with auto
, the return type will be specified after the parameters and a ->
sequence. That is, all that does is to declare main()
to return int
.
The significance of trailing return types is primarily for function template where it is now possible to use parameters to the function together with decltype()
to determine the return type. For example:
template <typename M, typename N> auto multiply(M const& m, N const& n) -> decltype(m * n);
This declares the function multiply()
to return the type produced by m * n
. Putting the use of decltype()
in front of multiply()
would be invalid because m
and n
are not, yet, declared.
Although it is primarily useful for function template, the same notation can also be used for other function. With C++14 the trailing return type can even be omitted when the function is introduced with auto
under some conditions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With