Function - return value?

Please check the FAQ (https://www.xyplorer.com/faq.php) before posting a question...
Post Reply
highend
Posts: 14950
Joined: 06 Feb 2011 00:33
Location: Win Server 2022 @100%

Function - return value?

Post 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?
One of my scripts helped you out? Please donate via Paypal

PeterH
Posts: 2827
Joined: 21 Nov 2005 20:39
Location: DE W11Pro 24H2, 1920*1200*100% 3840*2160*150%

Re: Function - return value?

Post 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

highend
Posts: 14950
Joined: 06 Feb 2011 00:33
Location: Win Server 2022 @100%

Re: Function - return value?

Post by highend »

Thanks PeterH :)

I'll use

Code: Select all

return "";
...
One of my scripts helped you out? Please donate via Paypal

Post Reply