andrewducker (
andrewducker) wrote2010-02-11 03:11 pm
![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
Thinking about code
If I have a method:
int DoSomething(string someStuff)
{
//Do Stuff
return 42;
}
then effectively I have an unnamed variable that gets set by the return statement, yes?
That being the case, wouldn't it be in some ways clearer to have an explicit, named, variable that gets set instead?
int DoSomething(string someStuff)
{
//Do Stuff
returnValue = 42;
}
where "returnValue" is a keyword that's used to return the value.
As it is I frequently end up with code that creates (or sets) a variable at various points through the code just so it can be returned at the end. Making this an explicit part of the language just makes sense to me.
I assume there are languages out there that do this.
int DoSomething(string someStuff)
{
//Do Stuff
return 42;
}
then effectively I have an unnamed variable that gets set by the return statement, yes?
That being the case, wouldn't it be in some ways clearer to have an explicit, named, variable that gets set instead?
int DoSomething(string someStuff)
{
//Do Stuff
returnValue = 42;
}
where "returnValue" is a keyword that's used to return the value.
As it is I frequently end up with code that creates (or sets) a variable at various points through the code just so it can be returned at the end. Making this an explicit part of the language just makes sense to me.
I assume there are languages out there that do this.
no subject
no subject
As the calling function, you'll assign the result to a variable of your choice (or not assign it at all, if you can do that sort of thing and you only care whether the function returned e.g. a true value, or you'll pass the value to a switch statement).
no subject
no subject
no subject
Let's have another example:
void MyMethod(string input, out string output)
{
output = input + " was processed";
}
That's perfectly valid C# syntax - and works fine. No need for a return - all I have to do is make sure that I set "output" sometime before the end of the method.
What I'd like is for _all_ output variables (including the implicit one) to work that way.
no subject
As an extreme example, imagine that the function is called in the context
if (DoSomething(x)) {
... stuff
} else {
... other stuff
}
The compiler should never actually store "42" but will instead elide the else branch of the test.
no subject
no subject
One variant of this optimisation which is more common, though, is returning an object by value and assigning to a class constructed at that point:
Foo x = somefunction();
For some compilers the object will be constructed once, at the higher level, and there will be no temporary variable of that type in the returned data on the stack (which will be data required to initialize the object -- the difference obviously being that operations in the constructor are called only once).