question about returning value of a function

B

Bob

Hi,

i'm not sure to understand how a value is returned from a function.
Look at this code below about a simple function that compares a value with
values 1 from 5.
I thought: if the passed value (x = test(?)) is not from 1 to 5, then the
return = -1. That's ok.
If not, the function will return value z, but at the end of the for/next
loop, the other return (return -1) will also be executed, no? The line
'return -1' is outside of the loop and will be executed in all cases?

Thanks
Bob


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Dim x As Integer
x = test(6)
Response.Write(x)
End Sub
Function test(ByVal z As Integer) As Integer
Dim i As Integer
For i = 1 To 5
If z = i Then
Return z
End If
Next
Return -1
End Function
 
B

Bob

Thanks, but in the code i used as example, there was no EXIT function. So
why will the Return -1 not be executed if the comparaison is true?
 
H

Herfried K. Wagner [MVP]

Just Me said:
For i = 1 To 5
If z = i Then
Return z
Exit Function '// ADD THIS LINE
End If
Next

This line will never be executed because the method will be leaved when
'Return z' is executed.
 
T

Tom Leylan

The return statement is an instruction to "return" along with the value to
return so yes you will get a -1 in your test sample. The line Return -1 is
outside the loop but no it won't be executed in all cases. If the value
passed is between 1 and 5 the earlier return statement will exit the
function.

That said (if you're developing good habits) you should reduce the number of
return statements (ideally to one) and it should generally be at or near the
end of the function. This can be accomplished by assigning a return
variable (as needed in the routine) and returning it as the routine exits.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top