B-A-S-I-C question

Blitz3D Forums/Blitz3D Beginners Area/B-A-S-I-C question

Who was John Galt?(Posted 2003) [#1]
I've done a lot of programming in my time- I should know this one, but.......

Is it bad for any reason to have a conditional return in the middle of a loop in a function?


JazzieB(Posted 2003) [#2]
You need to make use of the Exit command and have the Return outside of the loop, thus...

Function test()
  z = False
  For i = 0 to 30
    If i = 15 Then z = True:Exit
  Next
  Return z
End Function


You can't jump out of the middle of a loop, as the rest of the program would still think it's in one the next time it gets to a Next - provided Blitz will even compile such a program without an error.

The Exit command is used to jump out of any loop (For..Next, Repeat..Until/Forever and While..Wend).

Hope that helps.


Who was John Galt?(Posted 2003) [#3]
Cheers!


Difference(Posted 2003) [#4]
It's quite safe and there are no problems.
Like this:

Function FindTypeByID.mytype(id)
	For m.mytype = Each mytype
		If m\id = id Return m
	Next 
End Function



WolRon(Posted 2003) [#5]
Sounds like we have two conflicting theories. So which is it?


Beaker(Posted 2003) [#6]
I agree with Peter Shootz.


Rob(Posted 2003) [#7]
Peter is correct.


soja(Posted 2003) [#8]
The compiler knows which Nexts belong to which Fors, and in the case of returning in the middle of the loop, it just pops everything (variables, function call, etc) off the heap/stack, and everything's hunky-dory.

You might use the Exit command if you weren't in a function and/or didn't want to return straight away.

The only reason returning in the middle of a loop might be "bad" is that it's generally frowned upon by "professional" programmers, i.e. so called Code Grammarians (so called by me).


Sunteam Software(Posted 2003) [#9]
Peter's example is good because it points out that time critical code can benefit by being able to exit early based on conditions thus saving valuable CPU cycles which otherwise would have been wasted on redundant checks.


Rob(Posted 2003) [#10]
The only reason returning in the middle of a loop might be "bad" is that it's generally frowned upon by "professional" programmers, i.e. so called Code Grammarians (so called by me).

Ever heard of getting the job done? I don't care what other people think my code looks like.

I would say it matters when using C++ and working in a team where you need to enforce coding practise, but in Blitz? nah :)


Who was John Galt?(Posted 2003) [#11]
Right cheers guys. I prefer speed over 'grammer' so its decided 4 me.


soja(Posted 2003) [#12]
Rob, my sentiments exactly.