While loop - time of exit - while-loop

This question applies I suppose to programming in general, but my application is built in MATLAB (based on C++):
In a while loop, if the while condition is no longer satisfied, does the loop run to its completion or does it exit at the exact moment that the conditions of the while loop are no longer satisfied?
e.g.
x = 1
while (x = 1)
{
x = 0
(some code)
}
In this case, does (some code) run?
PS. I know the syntax is terrible, it's just to illustrate the situation

It runs to completion. The while is only considered at entry to the loop block. So yes, (some code) does run.

it will only check at the entry of loop block. If it satisfies the condition, then it will run to completion, of course you can always choose to break the loop, if not then it will not enter the loop at all.

Related

VBA - Leave Do Until when specific row is reached

In my VBA Code i go from the last row in my table to the top of my table. But i want that the Do Until Loop ends when it reached Row 10.
Right now I am using this Do Until Loop:
Do
' Do Something
Loop Until ActiveCell.Address = "$N$10:$BI$10"
How do i have to change my code that it will stop when it reached row 10?
Assuming rest of code is correct use:
Loop Until ActiveCell.Row = 10
If that fails you problem is logic in other parts of your code ie. ActiveCell never reaches row 10.
To answer your question in more theoretical fashion. There are multiple ways of exiting Do loops in VBA.
The proper way
1.1. While or Until at the begining
This checks the condition first, if the condition is met, it enters the loop and repeat with the condition being met at the start of every loop.
Do While i <= 5
'#code here
Loop
These two are equivalent.
Do Until i > 5
'#code here
Loop
1.2. While or until at the end
This is almost the same as what is described above. The only difference being, with sole Do statement at the beginning, your code-block always gets executed at least once! This can be particularly useful, when you want to execute something at least once, but don't want it to repeat unless a condition is met.
Do
'#code here
Loop While i <= 5
or
Do
'#code here
Loop Until i > 5
The enforced way
You can exit out of any loop, including Do with the so called Exit statement. This escapes the currently ongoing Do loop upon reaching the statement no questions asked. While you usually should try to avoid using the Exit statement, as in majority of cases it is possible to avoid using it with a proper condition at the While or Until portion of your code, it can come in handy in some cases.
Additionally, keep in mind, inside nested Do loops, Exit always exits only the innermost loop. This means, this would exit only the loop inside and let the others run, acting as a weird form of Continue
Do While (handler = True)
Do
'# execute me
If weird_condition = True Then
Exit Do
' i return to the "handler" loop
End If
field = field + 1
Loop Until field = field_amount
Loop
The not so nice enforced way
Alternatively, you can stop the entire exution, with the Stop statement. I would strongly advise against doing this, but technically it is a possibility so I'm listing it here. Similarly like End it ends the execution, but unlike End (eg. End Sub), it does not close any files or clear any variables - so technically this means you could use it to exit a loop. I would however recommend simply using the Exit statement instead. Can't really think of a case when I would ever use this.

Is there an equivalent of Python's pass statement in VBA?

I would like to know if there is an equivalent of Python's pass statement in VBA.
I am using Excel 2016.
The use of Stop (see this answer) seems to be the best thing to do if you are looking for some "non-statement" that you can use to insert a breakpoint, because the Stop command causes the code to break when it is reached, i.e. you don't even need to mark it as a breakpoint because it is one.
You might also like to consider using Debug.Assert some_logical_expression, which will break automatically whenever the logical expression evaluates to False. So Debug.Assert False would be equivalent to Stop, and Debug.Assert x = 3 would be equivalent to If x <> 3 Then Stop.
In Python you need the Pass, because otherwise the methods will not run.
In VBA, its perfectly ok if you leave an empty method like this:
Public Function Foo() As String()
End Function
Maby you are looking for the "Stop" statement.
The good thing about it is that it doesn't clear your variables.
It depends what are you trying to achieve.
You may declare a Label and then use GoTo Label e.g. declare a label (like Skip:)in your code where you want to jump if a condition is met and then use GoTo Skip
Below is the small demo code to give you an idea about this...
Dim i As Long
For i = 1 To 10
If i = 5 Then GoTo Skip
MsgBox i
Next i
Skip:

What's the difference between GoTo, using a Select, and using separate function?

To start off, I know that using Goto is never a good idea. But I'm having a hard time seeing the difference between the following structures...All of them process conditions sequentially, stop processing when they find a true value, then return control to a specified location in the code (the next line, as that's where this particular 'GoTo' target is). What is the difference between:
Ifs with GoTo:
If ConditionA then 'This is designed to skip the evaluation of condition B if condition A is met.
Do something
Goto Resume
End If
If ConditionB then
Do something
Goto Resume
End If
Resume:
Select Case:
Select ConditionIsTrue 'This will also skip the evaluation of B if A is true.
Case A
Do something
Case B
Do something
End select
Separate sub:
EvaluateConditions(condition)
Sub EvaluateConditions(condition)
If A then
DoSomething
Exit Sub
End If
If B then
DoSomething
Exit Sub
End If
End Sub
In general,
'goto' transfers the control of execution to the label that you are assigning. The control never comes back to where you use 'goto'. As the program flow is altered altogether, it is not advisable to use 'goto'. It becomes hard to debug.
When you write a subroutine and call it from other part of your code, the control is transferred back to the called part of your code once the execution of subroutine is complete. Hence, unlike goto, the program flow will not be affected and is always advisable to use subroutines instead of goto.
In case of select statement, it is not much different from multiple 'if-else' statements. Instead of having too many 'if-else' you can use 'select' to have a more cleaner code.
Being specific to what you have asked, all three does the same and there is no difference as such. What you choose depends on your requirement, number of conditions, re-usability of the piece of code and future enhancements.
If you have a very few conditions ( 2 or 3) and if you are sure that the piece of code doesn't require future enhancements, it is 'ok' to use goto.(still not a great choice)
If the piece of code should be reusable or even otherwise, using subroutine is the best choice. In fact, even if you have a very few conditions, it is better to use 'select' statement within the subroutine so that your code looks clean and is easy to add further conditions in future.

How does VB.Net evaluate the end test of a FOR...NEXT loop?

I am teaching students about the FOR NEXT loop in VB.Net and I seem to be burdened with an understanding from learning Assembly language long ago. Trying to count the number of iterations that a line of code would do in several cases:
FOR x = 1 TO 1 (implied STEP 1)
(body)
NEXT x
Should do 1 loop, right? But I read the test as "until x is 1", so after the first loop, x becomes 2 and the test should not work.
How about: FOR x = 1 TO 1 STEP -1? Is your answer the same?
How about: FOR x = 1 TO 0 (implied STEP 1)? The body should never execute. But the test is "until x = 0", so it should cause an infinite loop as x climbs away from 0... Starting to see the issue?
How about: FOR x = 1 TO 0 STEP -1? Now it will do the body twice, right? But what is x at that point? -1. How did the test stop when it is one beyond what is says it will stop at?
I guess the compiler is actually testing until x = (endval) + stepval. I can visualize that in Assembler, but otherwise I confess that I can't see or explain to my students how this all actually works the way it is assumed it "should". (This question seems trivial with constants like "1", but imagine variables or other ways of creating the FOR loop parameters.) Can anyone shed some light? Thank you.
It seems Tony Hinkle provided the answer, but did so as a comment. So I'm providing the particular text he mentioned here, as an answer:
"When a For...Next loop starts, Visual Basic evaluates start, end, and step. Visual Basic evaluates these values only at this time and then assigns start to counter. Before the statement block runs, Visual Basic compares counter to end. If counter is already larger than the end value (or smaller if step is negative), the For loop ends and control passes to the statement that follows the Next statement. Otherwise, the statement block runs.
Each time Visual Basic encounters the Next statement, it increments counter by step and returns to the For statement. Again it compares counter to end, and again it either runs the block or exits the loop, depending on the result. This process continues until counter passes end or an Exit For statement is encountered.
The loop doesn't stop until counter has passed end. If counter is equal to end, the loop continues. The comparison that determines whether to run the block is counter <= end if step is positive and counter >= end if step is negative."
To help clarify:
FOR x = 1 TO 1 (implied STEP 1) will loop 1 time.
FOR x = 1 TO 1 STEP -1 will loop 1 time.
FOR x = 1 TO 0 (implied STEP 1) will never loop because counter is already past end.
FOR x = 1 TO 0 STEP -1 will loop twice

VBA: Why do people include the variable's name in a "Next" statement?

I have always written my For-loops like this:
For foo = 1 to 10
' do something
Next
However, when I read code snippets online, people always do this:
For foo = 1 to 10
' do something
Next foo
I have not noticed any difference between the two, and I can't find any documentation on next statement is more desirable. What is the difference between those two (if any)?
The counter after the Next statement is optional. It used to be required in BASIC-derived languages, but this is no longer the case in VBA.
You can check the VBA reference:
If you omit counter in a Next statement, execution continues as if counter is included. If a Next statement is encountered before its corresponding For statement, an error occurs.
The reason people still add the counter it to increase readability.
It's for when you have multiple for loops.
For example,
For i to j
For k to l
next k
next i
Otherwise, the next is ambiguous. It's not absolutely necessary, as the loop will still work without it, but it's just good practice to have it marked for the sake of anyone else reading your code.