//we all always specify the return type of a function because it is in the syntax.....but can anyone tell me what basic objective is served by us by specifying the function's return type..........means why did the syntax have to be made like this.....it could be that we could just return the value..
You have to specify the type in a function declaration because not all function declarations are definitions. For example, consider the following declaration that we could have if a return type wasn't required:
f(int x);
What is the type of f(42)? There's no way to know from this declaration, hence the return type is required to be specified.
Or, consider the following function with a definition (assume C is some class):
g(bool b) {
if (b) {
return C();
}
return 0.0;
}
What should the return type of g be? It could be double or it could be C.
The syntax "has to be like this" because C++ is built on C, which has practically no type inference. C++ could have been built on some other language, in which case this wouldn't "have to be made like this," but then C++ would be a completely different language.
Note that C++0x adds one place where a function return type can be deduced: if a lambda expression body consists of a single return statement, then the return type of the lambda is deduced to be the type of the expression from the return statement (if the lambda is of any other form, the return type is deduced to be void unless a return type is explicitly specified). So, the following are identical:
[]() -> int { return 42; }
[]() { return 42; }
Lambda expressions are special, though, since you can't declare a lambda without defining it.
Exactly from the same reason you specify the types of the arguments the function receives.
Also, assuming that you don't specify the return value --
function f( int x ) { if (x == 0) return x; else return (x == 0); }
What would f return?
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