mon 21 sept 2015 delayed slides
play

Mon., 21 Sept. 2015 (delayed slides) Conditional and unconditional - PowerPoint PPT Presentation

Mon., 21 Sept. 2015 (delayed slides) Conditional and unconditional branches The go to statement and Dijkstras letter In-class exercise: the C goto statement Conditional Branches Familiar to most novice programmers: if and


  1. Mon., 21 Sept. 2015 (delayed slides) Conditional and unconditional branches The “go to” statement and Dijkstra’s letter In-class exercise: the C “goto” statement

  2. Conditional Branches Familiar to most novice programmers: “ if ” and “ if-else ” statements “ switch ” statements (More about these on Wednesday) Basic idea: if (condition) then … else … It wasn’t always quite this easy, though ...

  3. The Good Old Days of FORTRAN Here is part of an old FORTRAN program: if (i+j-k)10,20,30 Evaluate i+j-k and take one of three branches: 10 print *,"i+j-k is negative" statement 10 if i+j-k < 0, go to 40 statement 20 if i+j-k = 0, 20 print *,"i+j-k is zero" statement 30 if i+j-k > 0 go to 40 (You can run this in the lab 30 print *,"i+j-k is positive" -- look for file “arith-if.for” in the repository and follow 40 stop instructions in comments.) end

  4. The Good Old Days of FORTRAN Things were slightly better with relational operators: if (i+j .lt. k)go to 10 if (i+j .eq. k)go to 20 print*,"i+j > k" go to 30 10 print*,"i+j < k" go to 30 20 print*,"i+j = k" 30 stop

  5. The “go to” Statement Notice how often “go to” appears in these two programs. This is an UNCONDITIONAL branch. Most early programming languages had “go to” statements. Later languages like C also adopted them. They were easy to misuse, however:

  6. The “go to” Statement (Contrived) Example (in C): OUTPUT: for (i = 0; i < 5; i++) { inside if (i==3) goto OUTSIDE; inside INSIDE: printf(“inside\n”); inside } outside goto FINISH; inside inside OUTSIDE: printf(“outside\n”); goto INSIDE; FINISH: ...

  7. The “go to” Statement Edsger W. Dijkstra (world famous computer scientist -- “Dijkstra’s Algorithm”, etc.) wrote a letter to the Communications of the ACM in 1968:

  8. The “go to” Statement HUGE response. Letter is now famous; many imitations. “Considered harmful” essays appear about almost every topic in computer science: ● XMLHttpRequest Considered Harmful ● Csh Programming Considered Harmful ● Turing Test Considered Harmful ● Considered Harmful Essays Considered Harmful ● … etc. ...

  9. The “go to” Statement But why? C example shows that we can “break out of scope” with a goto (the for -loop block might have its own local variables); we can write incomprehensible code (“spaghetti code”); and many other problems arise. IN-CLASS EXERCISE: write some spaghetti code–get it out of your system! (See website.)

Recommend


More recommend