Page 1 of 1

Function - return value?

Posted: 21 Apr 2015 23:35
by highend
E.g.:

Code: Select all

// Resolve the volume serial number and return the corresponding drive letter
function resolveVolumeSerialNumber($vsn) {
    foreach($drive, get("drives")) {
        $drive = trim($drive, "\", "R");
        $match = regexmatches(runret("cmd /c vol $drive", "%windir%"), "[A-Z0-9]{4}-[A-Z0-9]{4}");
        if ($match == $vsn) { return $drive; }
    }
    return "";
}
The first "return $drive" is imho fine, the function exits on the first match.

How should the last return statement look like (I guess the best way is to return an empty string)?

- return;
- return "";
- remove it?

The call to the function looks like:

Code: Select all

$serial = "1ECD-8A2C";
    $dst = resolveVolumeSerialNumber($serial);
    if ($dst) { goto $dst; }
I don't want the function to return the current path if there is no match for the $vsn parameter because this could lead to a removed virtual filter / quick search...

Is there a better way to handle either the call or the function itself?

Re: Function - return value?

Posted: 22 Apr 2015 01:03
by PeterH
Hm - thanks for bringing me to look at that :whistle:

Till now I expected that return only sets the return value - but doesn't end the function execution. That was wrong! :oops:

So
1) Return returns a value and terminates the function
2) If the end of the function is reached without executing a return, nothing is returned. If a variable expects a value, "" seems to be returned.

So you can chose what to do - dependent from what you think is best.
Usually I think "" for having no return value is OK - then you can leave out the last return. (Or "demonstrate" it with return "";)
If you want to signal some special code use return to return it.

My point of view.
And thanks again for waking me up

Re: Function - return value?

Posted: 25 Apr 2015 08:08
by highend
Thanks PeterH :)

I'll use

Code: Select all

return "";
...