c++c++14return-type-deduction

Why can the return type of main not be deduced?


As expected, the following fails in C++11 because that language does not have return type deduction for bog standard functions:

auto main()
{
   return 0;
}

However, C++14 does, so I cannot explain the following error (with equivalent outcomes in GCC trunk, clang 3.8 and Visual Studio 2015):

error: 'main' must return 'int'

Is there a passage in the standard that I'm not seeing, forbidding return type deduction for main? Or are both compilers non-compliant?

(For what it's worth, I'd never actually do this. int main() for the win…)


Solution

  • Reading the C++17 draft §3.6.1/2:

    ... and it shall have a declared return type of type int, ...

    So yes I would say it's forbidden to use deduction.


    Almost the exact same wording in the last C++14 draft (same section as the C++17 draft):

    It shall have a declared return type of type int, ...


    Just a personal reflection on the possible reasoning behind this, after reading comments and other answers. The reasoning return-type deduction is not allowed is (I think) because then the return type isn't known by the compiler until it sees a return statement. It's also not uncommon that other types (that are implicitly convertible to int) might be returned which would make the deduced type wrong. Declaring the return type up-front (either by the normal old-fashioned way, or by using trailing return type) will set the type when the function is declared, and can be checked by the compiler then and there to be correct.

    As for allowing type-aliases, they are just aliases of a type. So allowing e.g.

    typedef int my_type;
    my_type main() { ... }
    

    is really no different from

    int main() { ... }