B-A-S-I-C question
Blitz3D Forums/Blitz3D Beginners Area/B-A-S-I-C question
| ||
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? |
| ||
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. |
| ||
Cheers! |
| ||
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 |
| ||
Sounds like we have two conflicting theories. So which is it? |
| ||
I agree with Peter Shootz. |
| ||
Peter is correct. |
| ||
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). |
| ||
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. |
| ||
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 :) |
| ||
Right cheers guys. I prefer speed over 'grammer' so its decided 4 me. |
| ||
Rob, my sentiments exactly. |