Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of auto main()->int?

Tags:

c++

c++11

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.

like image 299
StackIT Avatar asked Jan 13 '14 06:01

StackIT


1 Answers

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.

like image 72
Dietmar Kühl Avatar answered Sep 20 '22 00:09

Dietmar Kühl