Thread: Good examples of using goto and continue

  1. #1
    Registered User
    Join Date
    May 2015
    Posts
    228

    Question Good examples of using goto and continue

    In my c programming book that I'm currently reading, the author said that both goto and continue are both rarely used in any program and should be avoided whenever possible and that there are some exceptions where it is preferable to use these keywords(or any other keyword that changes state like break, return, etc). What would be an instance where it would make to sense to use goto or continue and not have it mess up your program(especially goto)?
    Last edited by deathslice; 05-06-2015 at 01:52 PM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by deathslice
    both goto and continue are both rarely used and should be avoid whenever possible and that there are some exceptions where it is preferable to use these keywords. What would be an instance where it would make to sense to use goto or continue and not have it mess up your program(especially goto)?
    Whether they are actually preferable to alternatives is debatable, but there are a few legitimate situations, e.g., for goto:
    • Instead of repeating cleanup code or moving it to a separate helper function, one could place the cleanup code with a label towards the end of the function then use goto as part of error handling.
    • Break out of nested loops, though it may or may not be better than simply making better use of loop conditions, e.g., with a flag.

    For continue, perhaps one could use it similiarly to how one might return early from a function say for error handling, except that it goes to the next iteration early instead. On the other hand, perhaps this is a sign that the body of the loop should be moved to a function. If the body of the loop is small enough that moving it to a function is unnecessary complication, then perhaps merely negating the condition would suffice, i.e., instead of:
    Code:
    while (condition1)
    {
        if (condition2)
        {
            continue;
        }
        foo();
    }
    one would write:
    Code:
    while (condition1)
    {
        if (!condition2)
        {
            foo();
        }
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    May 2015
    Posts
    228
    Alright thanks for an explanation.

  4. #4
    Registered User
    Join Date
    May 2015
    Posts
    228
    Well here is an example of using goto

    Code:
    # include <stdio.h>
    
    int main()
    {
       float num,average,sum;
       int i,n;
    
       printf("Maximum no. of inputs: ");
       scanf("%d",&n);
    
      for(i=1;i<=n;++i)
      {
           printf("Enter n%d: ",i);
           scanf("%f",&num);
    
           if(num<0.0)
           goto jump;
    
           sum=sum+num;
      }
    
      jump:
      average=sum/(i-1);       
      printf("Average: %.2f",average);
    
      return 0;
    }
    and here is a slightly different version of it.

    Code:
    #include <stdio.h>
    
    int main()
    {
       float num, average, sum;   
       int i, n;
    
        printf("Maximum no. of inputs: ");
        scanf("%d",&n);
    
    
        for(i=1; i<=n; i++)
        {
            printf("Enter n%d: ",i);
            scanf("%f",&num);
    
    
            if(num<0.0)
            {
                average=sum/(i-1);
                printf("Average: %.2f",average);
                return 0;
            }
            else
                sum+=num;
        }
    
    
        average=sum/(i);
        printf("Average: %.2f",average);
    
    
        return 0;
    }
    Questions:

    Is the second version any better than the first in terms of unnecessary code(is the program more compact and concise)?
    is there any way that you would have modified the first version without use of keyword like return, break, goto, etc?
    Last edited by deathslice; 05-06-2015 at 02:39 PM.

  5. #5
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Why not rework the example to avoid the goto, break, continue and the extra return?

    Code:
    #include <stdio.h>
    
    int main()
    {
       float num = 0.0, average = 0.0 ,sum = 0.0;
       int i = 0, n = 0;
    
       printf("Maximum no. of inputs: ");
       scanf("%d",&n);
    
       while(i < n || num < 0.0)
       {
          printf("Enter number %d: ", i + 1);
          scanf("%f",&num);
          if(num >= 0.0)
          {
             sum += num;
             ++i;
          }
       }
    
       average = sum / i;
       printf("Average: %.2f\n", average);
    
       return 0;
    }
    Jim

  6. #6
    Registered User
    Join Date
    May 2015
    Posts
    228
    Well, that was one my question: "is there any way that you would have modified the first version without use of keyword like return, break, goto, etc?" and your example is, at least to me, much better. In the future, I think it would be better for me to think before coding, the best way to execute a task without using unnecessary code.

  7. #7
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Quote Originally Posted by deathslice View Post
    Well, that was one my question: "is there any way that you would have modified the first version without use of keyword like return, break, goto, etc?" and your example is, at least to me, much better. In the future, I think it would be better for me to think before coding, the best way to execute a task without using unnecessary code.
    Thinking about code before writing it is good. Planning code before writing it is even better.

    When it comes to generating basic logic, my own preferred method is a flow chart. It doesn't even have to be fancy ... just a square for an action, and a diamond for a decision (with "true"/"false" paths).

    If you get the criteria down ... and plan the flow of logic ... your resulting code will be amazingly better. And in most cases without the need for "goto", etc.

    You need to see the logic, in a way that's comfortable and easy to digest. When you sit down with a pen and paper, you can put your thoughts into images, and then find a way to express those thoughts in basic logic. Think about it, break it down, and really get a grasp of the concepts you're trying to express.

    Plot it out and see the logical flow and connections ... by hand, on paper. Read what you did, think about it some more ... and you'll find improvements in your logic. Follow the arrows and the action, and you'll find way to improve your ideas.

    When you're done, you'll have a "road-map" of logic that is relatively easy to express in code.

    Code is cheap - that is the road you take on the way to a destination. Logical thinking ... that is the currency that will ensure a comfortable journey along the way.

  8. #8
    Registered User
    Join Date
    May 2015
    Posts
    228
    Well said.

  9. #9
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    If you're processing a collection in a loop and want to skip some of the items, I prefer to use continue. For example, suppose I am processing a file line by line and want to ignore blank lines and comment lines. This is the correct way to write that:

    Code:
    while (fgets(ln, MAX, stdin)) {
        if (is_blank(ln)) continue;
        if (is_comment(ln)) continue;
    
        /* process line ... */
    }
    You can always emulate the 'continue' by rearranging things. But remember the whole reason you want to avoid break, continue, goto is to avoid convoluted code. If the above example is convoluted, it certainly is not due to using 'continue'. If you were the kind of person who is blindly following the "don't ever use continue" rule, then the above loop will probably end up looking like this instead:

    Code:
    while (fgets(ln, MAX, stdin)) {
        if (!is_blank(ln) && !is_comment(ln)) {
            /* process line ... */
        }
        // NB: please don't put any code here
    }
    This version is inferior to me because it adds an extra level of indentation for no reason. Plus in this version you really need to make sure you don't put any code right before the closing brace of the loop if you want to properly emulate 'continue'. In real code, people never add such a comment so when you review the code you have to carefully make sure that no surprise code gets added after your monster if block exits.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by c99tutorial
    If you were the kind of person who is blindly following the "don't ever use continue" rule, then the above loop will probably end up looking like this instead:

    Code:
    while (fgets(ln, MAX, stdin)) {
        if (!is_blank(ln) && !is_comment(ln)) {
            /* process line ... */
        }
        // NB: please don't put any code here
    }
    This version is inferior to me because it adds an extra level of indentation for no reason. Plus in this version you really need to make sure you don't put any code right before the closing brace of the loop if you want to properly emulate 'continue'. In real code, people never add such a comment so when you review the code you have to carefully make sure that no surprise code gets added after your monster if block exits.
    As I mentioned in post #2, I think that this is better than using continue, given that there are few conditions. I do not see the "extra" level of indentation as being for "no reason": it reminds the reader that there is a selection going on in the loop. The problem is that when there are too many conditions, using continue (or in a function, doing an early return: after all, with many conditions chances are moving the code to a separate function would be a good idea) is better because one would otherwise either end up with a hard to read long condition, or there would indeed be excessive nesting.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Good examples/uses of bitwise operations?
    By MutantJohn in forum C Programming
    Replies: 18
    Last Post: 10-18-2013, 10:46 AM
  2. Replies: 27
    Last Post: 07-04-2013, 09:55 AM
  3. Good bitshifting tutorial or examples?
    By Striph in forum C++ Programming
    Replies: 2
    Last Post: 10-07-2012, 02:58 AM
  4. what are some good C++ source code examples?
    By orion- in forum C++ Programming
    Replies: 4
    Last Post: 09-13-2005, 09:24 PM
  5. FAQ: Examples of good questions (General)
    By Prelude in forum FAQ Board
    Replies: 1
    Last Post: 10-11-2002, 08:57 PM

Tags for this Thread