The new C++11 standard adds a new function declaration syntax with a trailing return type:
// Usual declaration
int foo();
// New declaration
auto foo() -> int;
This syntax has the advantage of letting the return type be deduced, as in:
template<class T, class U>
auto bar(T t, U u) -> decltype(t + u);
But then why the return type was put before the function name in the first place? I imagine that one answer will be that there was no need for such type deduction in that time. If so, is there a reason for a hypothetical new programming language to not use trailing return type by default?
As always, K&R are the "bad guys" here. They devised that function syntax for C, and C++ basically inherited it as-is.
Wild guessing here: In C, the declaration should hint at the usage, i.e., how to get the value out of something. This is reflected in:
int i;
, int
is accessed by writing i
int *p;
, int
is accessed by writing *p
int a[n];
, int
is accessed by writing a[n]
int f();
, int
is accessed by writing f()
So, the whole choice depended on the "simple values" case. And as @JerryCoffin already noted, the reason we got type name
instead of name : type
is probably buried in the ancient history of programming languages. I guess K&R took type name
as it's easier to put the emphasis on usage and still have pointers etc. be types.
If they had chosen name : type
, they would've either disjoined usage from declarations: p : int*
or would've made pointers not be types anymore and instead be something like a decoration to the name: *p : int
.
On a personal note: Imagine if they had chosen the latter and C++ inherited that - it simply wouldn't have worked, since C++ puts the emphasis on types instead of usage. This is also the reason why int* p
is said to be the "C++ way" and int *p
to be the "C way".
If so, is there a reason for a hypothetical new programming language to not use trailing return type by default?
Is there a reason to not use deduction by default? ;) See, e.g. Python or Haskell (or any functional language for that matter, IIRC) - no return types explicitly specified. There's also a movement to add this feature to C++, so sometime in the future you might see just auto f(auto x){ return x + 42; }
or even []f(x){ return x + 42; }
.