Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Other Discussions
  3. The Weird and The Wonderful
  4. Gotoless programming

Gotoless programming

Scheduled Pinned Locked Moved The Weird and The Wonderful
73 Posts 47 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Lost User

    That's why I always get scared when such rules are preached religiously and then applied at all cost. I often write code for old 8 bit computers or microcontrollers and calling functions for everything will result in a slow processor working more on the stack than the actual task. Using goto or branching instructions in assembly then will make more of the two most valuable resources, CPU and memory. Thinking and making most of the resources at your disposal is more important than blindly following rules.

    I'm invincible, I can't be vinced

    P Offline
    P Offline
    Peter Grogono
    wrote on last edited by
    #47

    You have to be pretty ancient to appreciate the goto controversy. I was writing FORTRAN in the mid-sixties and my oh-so-clever programs were an unreadable tangle opf goto's and labels. My initial response to Dijkstra's letter was "program without goto - impossible!". But I soon saw the need for sensible control structures. Also, I see goto-restriction as a high-level language issue. I have never hesitated to use goto (or equivalent) instructions in assembly-language programming - often because there's nothing else. But knowing high-level control structures certainly improved my assembly style.

    1 Reply Last reply
    0
    • G George Dennie

      Yep, seems like goto used to implement a simple "Case" statement to me too. In fact, "If", "Case", "For", "While" are just patterns captured from observing the repeated use of "Goto"; I would imagine. Thereby simplifying the language so you as the read don't have to search through the connecting statements to realize the "Goto" is just implementing a "While" or "If" pattern. Of course not all conceivable "Goto" pattern has been captured. Consequently, there are no doubt algorithms in which the "Goto" is either necessary or a simplier description than combinations of the aforementioned patterns, as rare as these may be.

      C Offline
      C Offline
      cpkilekofp
      wrote on last edited by
      #48

      George Dennie wrote:

      Of course not all conceivable "Goto" pattern has been captured. Consequently, there are no doubt algorithms in which the "Goto" is either necessary or a simplier description than combinations of the aforementioned patterns, as rare as these may be.

      Theoretically, ANY goto can be replaced with a finite state machine. Practically speaking, after ten years of trying I still never eliminated two goto's in a C module that did some rather hairy financial estimation at a former employer of mine, and I did eliminate the other several dozen or so that originally decorated the same module. It wasn't that it couldn't be eliminated, it was that the refactoring necessary to eliminate it was always too painful for the time we wanted to spend. The fact is, though, that it's much easier to teach someone how a piece of structured code works than it is to teach how a piece of spaghetti code works. That same module was one evil monster to troubleshoot when it had its maximum lifetime gotos because it was not structured; I got permission to eliminate the gotos because the original guys who wrote it were gone, and even the owner/entrepeneur who'd come up with the algorithm couldn't explain exactly how the code was doing it, so any attempt to update or enhance it required hours to days of analysis first; after I got done, that time spent went down by at least 90%. When you're not living with a piece of code but simply visit it every now and then, it does not pay to use any technique that you may not be able to understand easily a year or two later, especially if it's not your code but your employer's.

      1 Reply Last reply
      0
      • A andrewgissing

        Inspired by the goto comments in the lounge today... Msny years ago a co-worker showed me his first program after we had banned the use of goto statements at our company. His program had a main loop like: If var = 1 gosub 100 If var = 2 gosub 200 and so on.. and inside each subroutine before leaving, it would set var to whatever it needed to be next. An abstracted goto ! This is back in the days before OO and events. This was procedural type code and in this case.. a goto would have been clearly easier to understand.

        S Offline
        S Offline
        SeattleC
        wrote on last edited by
        #49

        Haters being haters again. Sigh. A little historical context might be helpful here. If you never programmed in a circa 1980 BASIC, the language did not provide named subroutines or structured control statements, symbolic labels or indentation. GOTO was all you had. To complain about GOTO in a language that has nothing else is just hating. This code implemented a very structured thing, a finite state machine. It was actually best practice for this language that the states were in subroutines and the GOSUBs in the main loop were all together. Back in the 1960's when many of your moms and dads were children, W Edsgar Dijkstra penned his fameous "GOTO Considered Harmful" article, and Ed Yourdon and others kicked off the "Structured Programming" movement, with its emphasis on single-entry/single-exit programming. (The structured programming movement was a good idea, but it had the same high hype-to-value ratio as Agile does today.) Languages of the day, led by PASCAL, went a little too far, requiring for instance that all functions return out the bottom, so that you often had to use a bit of state to guard if and while statements (WHILE NOT DONE AND ...) so execution would flow down the page and out the end of the function. People used this as evidence that we did so need GOTO. Then C came along with its break, continue, and return statements and relaxed the rules a bit. There were arguments from the SP folks that these statements were a bad thing, but practitioners won the day. There were GOTOs to exit code that returned resources. These, said GOTO fans, were evidence that GOTO was unavoidable. This was mostly hogwash, as you could test most resources to see if they'd been allocated, and only return the ones that were. And the arrival of exception handling and the resource-allocation-is-initialization idiom in C++ rendered that discussion moot. GOTO has few places left to hide. I haven't needed to use a GOTO since 1995, and I have cleaned up many a function by removing GOTOs and fixing up the logic to make it simpler and more correct. I would not miss GOTO if it were removed from C++. It's only there (like many C++ features) for compatibility with old and poorly written C programs. [pours gasoline on the fire]

        1 Reply Last reply
        0
        • A andrewgissing

          Inspired by the goto comments in the lounge today... Msny years ago a co-worker showed me his first program after we had banned the use of goto statements at our company. His program had a main loop like: If var = 1 gosub 100 If var = 2 gosub 200 and so on.. and inside each subroutine before leaving, it would set var to whatever it needed to be next. An abstracted goto ! This is back in the days before OO and events. This was procedural type code and in this case.. a goto would have been clearly easier to understand.

          M Offline
          M Offline
          Member 2053006
          wrote on last edited by
          #50

          Why use all of those ifs? There is an 'on gosub' statement in a lot of BASIC implementations. Yep, it sure is a horror. Just because goto would be better in this instance does not make goto any less of a horror in my opinion.

          1 Reply Last reply
          0
          • OriginalGriffO OriginalGriff

            I can understand it. There are indeed times when goto makes sense. The problem is that it is taught to people who do not have the experience to understand when those times are, so use it when a "proper" alternative would be more work. Blame the teachers! I do... :laugh:

            Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

            S Offline
            S Offline
            SortaCore
            wrote on last edited by
            #51

            Wish it was more obvious in tutorials. The impression I get is "Don't ever use goto". That just made me wonder why switch/cases use the same syntax. Anyone have a link to explain when it's a good idea?

            OriginalGriffO A A 3 Replies Last reply
            0
            • C ClockMeister

              CDP1802 wrote:

              Thinking and making most of the resources at your disposal is more important than blindly following rules.

              Well said. My thoughts exactly. It's a matter of the right tool for the job. This is true in any field of endeavor. You use a spoon when you need one and a front-end loader when you need one of those. You don't just say "never use a spoon" once you've discovered that you have a front-end loader at your disposal. You use whichever one suits the job at hand. GOTO makes sense in a lot of contexts, in others it doesn't. Whatever construct allows you to express the idea in code most elegantly is what you use. I have to laugh at the religious fervor that develops over this particular subject. -Max

              C Offline
              C Offline
              cpkilekofp
              wrote on last edited by
              #52

              CodeBubba wrote:

              GOTO makes sense in a lot of contexts, in others it doesn't. Whatever construct allows you to express the idea in code most elegantly is what you use.
               
              I have to laugh at the religious fervor that develops over this particular subject.

              It's not religious fervor; it's the voice of victims of the GoTo Holocaust saying "Never again!" I speak for myself and many, many others who had to maintain code written in structured languages by programmers who didn't care to structure their code. At the time I entered programming as a profession, Dykstra's "GoTo Considered Harmful" had been published for over a decade yet many programmers still disdained use of structures even after moving to languages like C which supported a rich set of control and loop structures. This was called "job security" - after all, if only the original programmer could explain his code, obviously he needed to be kept happy, and the less readable the code was the better it served the programmer's purpose. The biggest problem with GoTo is that is does NOT "express an idea"; it just tells you where to go next. Thus, while the code implements the algorithm, it does not express it to the reader. That hasn't kept me from occasionally letting a goto remain somewhere where it would have been too time-consuming to factor it out. Also, goto is vital in one particular context: when otherwise code would be too large for the available memory space. Before virtual memory (i.e. the days of MSDOS) I helped maintain multi-megabyte programs loaded 256k at a time into the PC's memory, and gotos could sometimes eliminate code repetition in complex algorithms that resisted refactoring (e.g. they worked, but no one really knew how). So, I do know that gotos are sometimes necessary. However, it is my considered opinion based on years of experience maintaining code with gotos along with years of experience first using structured programming then other forms (functional, declarative, later OOP) that if goto isn't absolutely required to solve the problem, then it is a maintenance menace because it does not express anything, requiring a programmer to parse the branches in order to understand the algorithm being expressed. This may not seem like anything to someone who routinely uses gotos, especially if you work within a group that shares the same habits and code styles, but do you remember how long it took to become an expert at what so

              C 1 Reply Last reply
              0
              • S SortaCore

                Wish it was more obvious in tutorials. The impression I get is "Don't ever use goto". That just made me wonder why switch/cases use the same syntax. Anyone have a link to explain when it's a good idea?

                OriginalGriffO Offline
                OriginalGriffO Offline
                OriginalGriff
                wrote on last edited by
                #53

                :laugh: No! It's not a hard and fast rule - it depends on the complexity of what you are doing and why you might need it. Sorry - but it's an experience thing, not something you can easily take down to a list of "if this and this and this, but not that or that, then..." It's like driving a car - after a while you get a feel for "Is now a good time to pull out of this side turning?". It's not something you can easily explain.

                Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water

                "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                1 Reply Last reply
                0
                • S SortaCore

                  Wish it was more obvious in tutorials. The impression I get is "Don't ever use goto". That just made me wonder why switch/cases use the same syntax. Anyone have a link to explain when it's a good idea?

                  A Offline
                  A Offline
                  archimboldo
                  wrote on last edited by
                  #54

                  Not that I have used it, but the case some have made is breaking out of deeply nested loops (and not with exceptions): for (i = 0; i < end; i++) { doSomething(); for(j = obj[i].getAnotherObj(); j++; obj[i].end()) { doSomethingElse(); for(k = anotherObj[j].getYetAnotherObj(); k++; anotherObj[j].end()) { if (yetAnotherObj[k].condition()) goto breakOutOfDeeplyNestedLoop; doYetSomethingElse(); } blahBlah(); } blahBlahBlah(); } breakOutOfDeeplyNestedLoop: moreStuffInThisMethod(); You could use exceptions, but that's really a misuse of them if the condition is not truly exceptional.

                  S 1 Reply Last reply
                  0
                  • C cpkilekofp

                    CodeBubba wrote:

                    GOTO makes sense in a lot of contexts, in others it doesn't. Whatever construct allows you to express the idea in code most elegantly is what you use.
                     
                    I have to laugh at the religious fervor that develops over this particular subject.

                    It's not religious fervor; it's the voice of victims of the GoTo Holocaust saying "Never again!" I speak for myself and many, many others who had to maintain code written in structured languages by programmers who didn't care to structure their code. At the time I entered programming as a profession, Dykstra's "GoTo Considered Harmful" had been published for over a decade yet many programmers still disdained use of structures even after moving to languages like C which supported a rich set of control and loop structures. This was called "job security" - after all, if only the original programmer could explain his code, obviously he needed to be kept happy, and the less readable the code was the better it served the programmer's purpose. The biggest problem with GoTo is that is does NOT "express an idea"; it just tells you where to go next. Thus, while the code implements the algorithm, it does not express it to the reader. That hasn't kept me from occasionally letting a goto remain somewhere where it would have been too time-consuming to factor it out. Also, goto is vital in one particular context: when otherwise code would be too large for the available memory space. Before virtual memory (i.e. the days of MSDOS) I helped maintain multi-megabyte programs loaded 256k at a time into the PC's memory, and gotos could sometimes eliminate code repetition in complex algorithms that resisted refactoring (e.g. they worked, but no one really knew how). So, I do know that gotos are sometimes necessary. However, it is my considered opinion based on years of experience maintaining code with gotos along with years of experience first using structured programming then other forms (functional, declarative, later OOP) that if goto isn't absolutely required to solve the problem, then it is a maintenance menace because it does not express anything, requiring a programmer to parse the branches in order to understand the algorithm being expressed. This may not seem like anything to someone who routinely uses gotos, especially if you work within a group that shares the same habits and code styles, but do you remember how long it took to become an expert at what so

                    C Offline
                    C Offline
                    ClockMeister
                    wrote on last edited by
                    #55

                    You may not have meant it but your tone is sanctimonious. If that's the way you intend it, it's not appreciated. No doubt, I have (over 35 years) cleaned up a lot of messes (spaghetti code) where GOTO was misused. When I say "a lot of contexts" I mean I have run into a lot of situations in existing code where its use still makes sense and where "factoring it out" isn't profitable. I practically never use it any more in my OO style code however, as it was pointed out earlier I believe, there are still situations (assembly code, etc) where it's use is appropriate. I repeat: use the right tool for the job. If a developer is incompetent then GOTO will not be his only abuse. -Max :-)

                    1 Reply Last reply
                    0
                    • S SortaCore

                      Wish it was more obvious in tutorials. The impression I get is "Don't ever use goto". That just made me wonder why switch/cases use the same syntax. Anyone have a link to explain when it's a good idea?

                      A Offline
                      A Offline
                      Ahmedn1
                      wrote on last edited by
                      #56

                      The main problem is that goto statement is the only instruction in all programming languages that can change the PC (Program Counter) register in the processor and this is not right

                      B 1 Reply Last reply
                      0
                      • A archimboldo

                        Not that I have used it, but the case some have made is breaking out of deeply nested loops (and not with exceptions): for (i = 0; i < end; i++) { doSomething(); for(j = obj[i].getAnotherObj(); j++; obj[i].end()) { doSomethingElse(); for(k = anotherObj[j].getYetAnotherObj(); k++; anotherObj[j].end()) { if (yetAnotherObj[k].condition()) goto breakOutOfDeeplyNestedLoop; doYetSomethingElse(); } blahBlah(); } blahBlahBlah(); } breakOutOfDeeplyNestedLoop: moreStuffInThisMethod(); You could use exceptions, but that's really a misuse of them if the condition is not truly exceptional.

                        S Offline
                        S Offline
                        SortaCore
                        wrote on last edited by
                        #57

                        Ah yes, in some of my console apps I have a while loop for the console input, with continue to indicate that the command was recognised and bypass the rest of the commands in the loop. Of course once I nested a for loop, I had to use a bool to ensure whether the loop should have used continue or not. So assuming a similar scenario, instead of

                        while(settext())
                        {
                        // Command 1 (no parameters)
                        if(!stricmp(text, "something"))
                        {
                        DoStuff();
                        continue; // Skip command 2-3 & error check
                        }

                        // Command 2 (single parameter - text to match)
                        if(!strincmp(text, sizeof("other thing ")-1, "other thing "))
                        {
                        for(unsigned int i = 0; i < StringArray.size(); ++i)
                        {
                        if(!stricmp(text+sizeof("other thing ")-1, StringArray[i]))
                        {
                        StringArray.erase(i);
                        break; // or use goto JumpHere?
                        }
                        }

                          // Did not find? You have to use a variable to check
                          ReportError("parameter not found");
                          continue; // Skip command 3 & error check
                        

                        }

                        // Command 3 (not set up)
                        if(!stricmp(text, "asparagus"))
                        {
                        continue; // Skip error check
                        }

                        // Error check
                        ReportError("command not found);
                        JumpHere:
                        continue; // Labels must have a statement
                        }

                        So that would be an applicable scenario?

                        M 1 Reply Last reply
                        0
                        • A andrewgissing

                          Inspired by the goto comments in the lounge today... Msny years ago a co-worker showed me his first program after we had banned the use of goto statements at our company. His program had a main loop like: If var = 1 gosub 100 If var = 2 gosub 200 and so on.. and inside each subroutine before leaving, it would set var to whatever it needed to be next. An abstracted goto ! This is back in the days before OO and events. This was procedural type code and in this case.. a goto would have been clearly easier to understand.

                          T Offline
                          T Offline
                          TNCaver
                          wrote on last edited by
                          #58

                          My signature line says it all.

                          If you think 'goto' is evil, try writing an Assembly program without JMP.

                          1 Reply Last reply
                          0
                          • S SortaCore

                            Ah yes, in some of my console apps I have a while loop for the console input, with continue to indicate that the command was recognised and bypass the rest of the commands in the loop. Of course once I nested a for loop, I had to use a bool to ensure whether the loop should have used continue or not. So assuming a similar scenario, instead of

                            while(settext())
                            {
                            // Command 1 (no parameters)
                            if(!stricmp(text, "something"))
                            {
                            DoStuff();
                            continue; // Skip command 2-3 & error check
                            }

                            // Command 2 (single parameter - text to match)
                            if(!strincmp(text, sizeof("other thing ")-1, "other thing "))
                            {
                            for(unsigned int i = 0; i < StringArray.size(); ++i)
                            {
                            if(!stricmp(text+sizeof("other thing ")-1, StringArray[i]))
                            {
                            StringArray.erase(i);
                            break; // or use goto JumpHere?
                            }
                            }

                              // Did not find? You have to use a variable to check
                              ReportError("parameter not found");
                              continue; // Skip command 3 & error check
                            

                            }

                            // Command 3 (not set up)
                            if(!stricmp(text, "asparagus"))
                            {
                            continue; // Skip error check
                            }

                            // Error check
                            ReportError("command not found);
                            JumpHere:
                            continue; // Labels must have a statement
                            }

                            So that would be an applicable scenario?

                            M Offline
                            M Offline
                            Mark Kruger
                            wrote on last edited by
                            #59

                            Good example exactly of not using goto at all, it's easily converted to an if then else situation. which increases readability if u would ask me.

                            while(settext())
                            {
                            // Command 1 (no parameters)
                            if(!stricmp(text, "something"))
                            {
                            DoStuff();
                            // continue; // Skip command 2-3 & error check
                            }

                            // Command 2 (single parameter - text to match)
                            else if(!strincmp(text, sizeof("other thing ")-1, "other thing "))
                            {
                            for(unsigned int i = 0; i < StringArray.size(); ++i)
                            {
                            if(!stricmp(text+sizeof("other thing ")-1, StringArray[i]))
                            {
                            StringArray.erase(i);
                            break; // or use goto JumpHere?
                            }
                            }

                              // Did not find? You have to use a variable to check
                              ReportError("parameter not found");
                            

                            // continue; // Skip command 3 & error check
                            }

                            // Command 3 (not set up)
                            else if(!stricmp(text, "asparagus"))
                            {
                            // continue; // Skip error check
                            }
                            else

                            {
                            // Error check
                            ReportError("command not found");
                            // JumpHere:
                            // continue; // Labels must have a statement
                            }
                            }

                            S 1 Reply Last reply
                            0
                            • A andrewgissing

                              Inspired by the goto comments in the lounge today... Msny years ago a co-worker showed me his first program after we had banned the use of goto statements at our company. His program had a main loop like: If var = 1 gosub 100 If var = 2 gosub 200 and so on.. and inside each subroutine before leaving, it would set var to whatever it needed to be next. An abstracted goto ! This is back in the days before OO and events. This was procedural type code and in this case.. a goto would have been clearly easier to understand.

                              P Offline
                              P Offline
                              Plamen Dragiyski
                              wrote on last edited by
                              #60

                              If I'm not sure will compiler will understand goto's replacement better, I prefer goto (never trust any compiler).

                              1 Reply Last reply
                              0
                              • C ClockMeister

                                CDP1802 wrote:

                                Thinking and making most of the resources at your disposal is more important than blindly following rules.

                                Well said. My thoughts exactly. It's a matter of the right tool for the job. This is true in any field of endeavor. You use a spoon when you need one and a front-end loader when you need one of those. You don't just say "never use a spoon" once you've discovered that you have a front-end loader at your disposal. You use whichever one suits the job at hand. GOTO makes sense in a lot of contexts, in others it doesn't. Whatever construct allows you to express the idea in code most elegantly is what you use. I have to laugh at the religious fervor that develops over this particular subject. -Max

                                J Offline
                                J Offline
                                jschell
                                wrote on last edited by
                                #61

                                CodeBubba wrote:

                                OTO makes sense in a lot of contexts, in others it doesn't.

                                I doubt that in the general sense and specifically for this site/forum. It could be that there is a problem domain like camera firmware where the context basically requires goto. However in the context of standard enterprise business development that is done in languages like Java, C# and/or C++ it almost never is needed.

                                1 Reply Last reply
                                0
                                • M Mark Kruger

                                  Good example exactly of not using goto at all, it's easily converted to an if then else situation. which increases readability if u would ask me.

                                  while(settext())
                                  {
                                  // Command 1 (no parameters)
                                  if(!stricmp(text, "something"))
                                  {
                                  DoStuff();
                                  // continue; // Skip command 2-3 & error check
                                  }

                                  // Command 2 (single parameter - text to match)
                                  else if(!strincmp(text, sizeof("other thing ")-1, "other thing "))
                                  {
                                  for(unsigned int i = 0; i < StringArray.size(); ++i)
                                  {
                                  if(!stricmp(text+sizeof("other thing ")-1, StringArray[i]))
                                  {
                                  StringArray.erase(i);
                                  break; // or use goto JumpHere?
                                  }
                                  }

                                    // Did not find? You have to use a variable to check
                                    ReportError("parameter not found");
                                  

                                  // continue; // Skip command 3 & error check
                                  }

                                  // Command 3 (not set up)
                                  else if(!stricmp(text, "asparagus"))
                                  {
                                  // continue; // Skip error check
                                  }
                                  else

                                  {
                                  // Error check
                                  ReportError("command not found");
                                  // JumpHere:
                                  // continue; // Labels must have a statement
                                  }
                                  }

                                  S Offline
                                  S Offline
                                  SortaCore
                                  wrote on last edited by
                                  #62

                                  I believe you read that wrong, please read the comments I have in the code. The point here was exiting out of the the for loop embedded in the while loop, not the if format ;) Although I am also interested if using if-else-if actually is faster than repetitive

                                  if() {code(); end_if_checks();} if() {...}

                                  in my example though.

                                  M 1 Reply Last reply
                                  0
                                  • S SortaCore

                                    I believe you read that wrong, please read the comments I have in the code. The point here was exiting out of the the for loop embedded in the while loop, not the if format ;) Although I am also interested if using if-else-if actually is faster than repetitive

                                    if() {code(); end_if_checks();} if() {...}

                                    in my example though.

                                    M Offline
                                    M Offline
                                    Mark Kruger
                                    wrote on last edited by
                                    #63

                                    If u want speed, i would const the size of for your fixed string, would safe u getting it's length each time u go for another loop in the while. The continues u fire are at end of each if slice, and in an if else construction it would jump out to bottom anyways, so in this case i think continue actually will be equally fast at best and else even slower.

                                    for(unsigned int i = 0; i < StringArray.size(); ++i)
                                    {
                                    if(!stricmp(text+sizeof("other thing ")-1, StringArray[i]))
                                    {
                                    StringArray.erase(i);
                                    break; // or use goto JumpHere?
                                    }
                                    }

                                    I normally do different, a bit slower i assume but clear

                                    //somewhere outside the while
                                    const int Sizer = sizeof("other thing ")-1;
                                    //

                                    int WalkTo = StringArray.size() - 1;

                                    if (WalkTo >= 0)
                                    {
                                    const char* Check = text + Sizer;
                                    int i = -1;
                                    int Found = 0;

                                    do
                                    {
                                       i++;
                                       if (!stricmp(Check, StringArray\[i\]))
                                       {
                                           StringArray.erase(i);
                                           Found = 1;
                                       }
                                    } while (!Found && (i < WalkTo));
                                    

                                    }

                                    S 1 Reply Last reply
                                    0
                                    • A Ahmedn1

                                      The main problem is that goto statement is the only instruction in all programming languages that can change the PC (Program Counter) register in the processor and this is not right

                                      B Offline
                                      B Offline
                                      BobJanova
                                      wrote on last edited by
                                      #64

                                      Clearly false since a whole bunch of language constructs compile into assembler/IL jump instructions.

                                      1 Reply Last reply
                                      0
                                      • L Lost User

                                        The good old goto debate. A goto is a bit like telling the computer that I don't want you to proceed to the next line of code, instead make some other line the next thing to execute. And we do that all the time: exit for, exit do, if some condition goto next line otherwise goto some other line. While some condition go into first line of loop block otherwise goto past the end of the loop block. And then, it all eventually becomes machine code / opcodes, and all of these become some kind of jump instruction, which is basically a goto. So for all you people out there that think that your code has no gotos, I can assure you the CPU is doing jump instructions left, right and centre as YOUR code runs in the CPU. Now please don't tell me that your code is somehow bypassing the CPU. The reason this myth exists is that those early versions of BASIC had line numbers for each statement. And you would code "GOTO 760". Problem was when you inserted lines and made 760 line 761 or whatever but didn't go and update everything pointing to 760. And so this caused problems and bugs. Let's move on. We have alphabetic statement labels (used all the time in assembly language by the way), so you can now "Goto SomeLabelThatHasAMeaningfulNameThatWontBeRenumbered" and the problem is gone. Use goto freely, it's OK. I do it. It gets me out of deep nested rules and condition logic where I have established something I needed to establish. Yes there are always other ways to achieve the same result, but no - they are not always better or more elegant. And now it is time for me to go to bed.

                                        L Offline
                                        L Offline
                                        Lost User
                                        wrote on last edited by
                                        #65

                                        This is a simplistic example of the sort of thing I am talking about. My sympathies to those of you who find it un-structured, hard to understand, un-clean or bad code. Let me see yours.

                                        if WageEarner then
                                        WeeklyPay = HrsWorked * Rate
                                        Goto WklyPayDetermined
                                        end if
                                        if SalaryEearner then
                                        WeeklyPay = (Salary * 7) / 365
                                        Goto WklyPayDetermined
                                        end if
                                        if FutureHire then
                                        WeeklyPay = 0
                                        Goto WklyPayDetermined
                                        end if
                                        if Retired then
                                        if WasWageEarner then
                                        WeeklyPay = FinalRate * 40 * 0.5
                                        Goto WklyPayDetermined
                                        else
                                        WeeklyPay = 0.6 * (Salary * 7) / 365
                                        Goto WklyPayDetermined
                                        end if
                                        end if

                                        WklyPayDetermined:

                                        TaxDeductible = WorkOutTax(WeeklyPay)

                                        CreateBankTransaction(WeeklyPay - TaxDeductible)

                                        1 Reply Last reply
                                        0
                                        • M Mark Kruger

                                          If u want speed, i would const the size of for your fixed string, would safe u getting it's length each time u go for another loop in the while. The continues u fire are at end of each if slice, and in an if else construction it would jump out to bottom anyways, so in this case i think continue actually will be equally fast at best and else even slower.

                                          for(unsigned int i = 0; i < StringArray.size(); ++i)
                                          {
                                          if(!stricmp(text+sizeof("other thing ")-1, StringArray[i]))
                                          {
                                          StringArray.erase(i);
                                          break; // or use goto JumpHere?
                                          }
                                          }

                                          I normally do different, a bit slower i assume but clear

                                          //somewhere outside the while
                                          const int Sizer = sizeof("other thing ")-1;
                                          //

                                          int WalkTo = StringArray.size() - 1;

                                          if (WalkTo >= 0)
                                          {
                                          const char* Check = text + Sizer;
                                          int i = -1;
                                          int Found = 0;

                                          do
                                          {
                                             i++;
                                             if (!stricmp(Check, StringArray\[i\]))
                                             {
                                                 StringArray.erase(i);
                                                 Found = 1;
                                             }
                                          } while (!Found && (i < WalkTo));
                                          

                                          }

                                          S Offline
                                          S Offline
                                          SortaCore
                                          wrote on last edited by
                                          #66

                                          Okay, let me add a line at the prefix to clear up any confusion:

                                          std::vector StringArray;

                                          The StringArray.size() gets the size of an array of std::strings, not an array of chars. Say the StringArray was initialised to a set of usernames, in a server for example, and the command 2 could be "disconnect xxx".

                                          M 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups