Monday, November 15, 2010

lecture

Goto statement
Goto label

jmp instruction in assembler
cmp, followed by a jnz instruction

for loop, while loop, examples of syntactic sugar


in BASIC, my first program:
10 Print "Hello"
20 Goto 10

in Visual Basic:
here:
    Debug.Print("Hello")
    Goto here
    Debug.Print("Goodbye")

an infinite loop never ends
how would we do this without Gotos?

Do
    Debug.Print("Hello")
Loop

    I = 0
here:
    Debug.Print("Hello" & I)
    I = I + 1
    If i < 3 Then
        Goto here
    EndIf

I = 0
Do
    Debug.Print("Hello" & I)
    I = I + 1
Loop While i < 3

' this is called a post-test

what if we want a pretest?
I = 0
Do While i < 3
    Debug.Print("Hello" & I)
    I = I + 1
Loop

I = 0
goto there
here:
    Debug.Print("Hello" & I)
    I = I + 1
there:
    If i < 3 Then
        Goto here
    EndIf

So why don't we use Gotos?!
1) simpler
2) higher
3) more controlled
4) spaghetti code

http://en.wikipedia.org/wiki/Spaghetti_code

10 i = 0
20 i = i + 1
30 PRINT i; " squared = "; i * i
40 IF i >= 10 THEN GOTO 60
50 GOTO 20
60 PRINT "Program Completed."
70 END

FOR i = 1 TO 10
    PRINT i; " squared = "; i * i
NEXT i
PRINT "Program Completed."
END

a move to eliminate gotos
Goto statement considered harmful

http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html

Goto statement considered harmful considered harmful

rules for using goto:
1) it should always be fairly close
2) only goto above you, never below you



  Dim response As Integer, quotation As String = ""

  Do
    response = CInt(InputBox("Enter a number from 1 to 3."))
  Loop Until response >= 1 And response <= 3

No comments:

Post a Comment