7

What's the difference between these two functions?

auto func(int a, int b) -> int;

int func(int a, int b);

3 Answers 3

10

Other than the notation, there isn't any difference in the above case. The alternative function declaration syntax become important when you want to refer to one or more of the arguments to determine the return type of the function. For example:

template <typename S, typename T>
auto multiply(S const& s, T const& t) -> decltype(s * t);

(yes, it is a silly example)

7
  • I never understood why a compiler can't handle the same with the old syntax, like: template <typename S, typename T> decltype(s * t) multiply(S const& s, T const& t); Do you know why?
    – leemes
    Dec 30, 2012 at 2:18
  • 3
    @leemes: It is possible that compilers could do the same with the old style syntax but C++ consistently follows the rule that no name is visible before it is declared. Whether this rule is a good rule to have is a separate question but the consistency helps. Dec 30, 2012 at 2:20
  • 1
    @billz: Of course, the lambda rules and the trailing return went somewhat hand in hand: If there were no trailing returns for function something different would be used for lambdas as well. I seem to recall that both notations were developed pretty much together. Dec 30, 2012 at 2:22
  • 2
    @leemes: Yes, that is correct but it doesn't break the rule: The member functions defined within a class definition are treated as if they are defined outside the class definition, immediately following the class definition. The member definitions inside the class are just a short-hand (although I'm not quite sure how this works with friend functions inside a class template as these cannot be defined outside the class definition). Dec 30, 2012 at 2:25
  • 1
    +1: silly example, perhaps, but a very precise one, none the less.
    – WhozCraig
    Dec 30, 2012 at 4:15
5

There is no useful difference between these two declarations; both functions return an int.

C++11's trailing return type is useful with functions with template arguments, where the return type is not known until compile-time, such as in this question: How do I properly write trailing return type?

2

They use different syntax and only one of them is valid in C++ versions prior to C++11. Other than that there are no differences between the two function declarations that you've shown in your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.