Thread: Alternative to goto?

  1. #1
    Registered User
    Join Date
    Aug 2012
    Posts
    10

    Alternative to goto?

    Hello people, I am new to this forum, this is my first post. I wanted to introduce myself and ask a question about this code

    Code:
    /* Game menu for any game - remember to specify functions */
    #include <stdio.h>
    
    void playgame()
    {
        printf( "Play game called" );
    }
    
    void loadgame()
    {
        printf( "Load game called" );
    }
    
    void playmultiplayer()
    {
        printf( "Play multiplayer game called");
    }
    
    int main()
    {
        int input;
    
        printf( "1. Play game\n" );
        printf( "2. Load game\n" );
        printf( "3. Play multiplayer\n" );
        printf( "4. Exit\n" );
        menu: ;
        scanf( "%d", &input );
        getchar();
    
        switch( input)
        {
            case 1:
                playgame();
                break;
            case 2:
                loadgame();
                break;
            case 3:
                playmultiplayer();
                break;
            case 4:
                printf( "Goodbye\n" );
                break;
            default:
                printf( "Bad input, try again\n" );
                goto menu;
                break;
        }
        getchar();
    }
    you see the goto menu; ? What can I do instead of that, many people don't like goto, and I am sure that a for loop can replace the goto (I think). Thanks for the reply.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    How about
    Code:
      do {
        scanf( "%d", &input );
        getchar();
    
        switch( input)
        {
            case 1:
                playgame();
                break;
            case 2:
                loadgame();
                break;
            case 3:
                playmultiplayer();
                break;
            case 4:
                printf( "Goodbye\n" );
                break;
            default:
                printf( "Bad input, try again\n" );
                goto menu;
                break;
        }
      while ( input != 4 );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Salem forgot to delete the "goto menu;" line.

    Do you have a decent book to learn from? If so, then where did this crappy code come from?

    Beginners need to stay away from goto in order to learn to properly use the structured control statements. Experts use goto occasionally in order to avoid cluttering the code with pointless flags that are tested multiple times for loop control. It can also be useful for error-handling.

    Similarly beginners should stay away from global variables in order to learn the proper use of function parameters. But experts use globals when the tradeoffs warrant it.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You menu, putting it together, might look like:

    Code:
    
      do {
    
        printf( "1. Play game\n" );
        printf( "2. Load game\n" );
        printf( "3. Play multiplayer\n" );
        printf( "4. Exit\n" );
        menu: ;
        scanf( "%d", &input );
        getchar();
    
        switch( input)
        {
            case 1:
                playgame();
                break;
            case 2:
                loadgame();
                break;
            case 3:
                playmultiplayer();
                break;
            case 4:
                printf( "Goodbye\n" );
                break;
            default:
                printf( "Bad input, try again\n" );
                break;
        }
    
      }while(input != 4);
    And welcome to the forum, Lyle!

  5. #5
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Grr, need to slap the person who ever told you about the existence of goto while you're still a beginner programmer. Please please forget it even exists.

    Almost nobody uses it in the real world and there is virtually no need for it.
    I haven't used one in a very long time, certainly never at work in the last 10 years. The only time I am ever reminded that it exists is when people like you post on here.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  6. #6
    Registered User
    Join Date
    Aug 2012
    Posts
    10
    Cool, I know of goto from.... Some C code I was looking at a while back? Lol I wanted to know if it existed in C... I already know that it is bad practice to use it most ANY situation, but I thought it would make it easier to ask my question... thanks guys, mark this as solved unless you want to rant about goto. And I am teaching myself... Feel free to point me to any helpful sources... and I fixed my menu for future games
    Last edited by .:Lyle:.; 08-26-2012 at 02:42 AM.

  7. #7
    Registered User
    Join Date
    Aug 2012
    Posts
    10
    Wait, sorry for the double post, but the above code does not work... I tried a few things out, but only when I put the scanf in a code block with the switch
    Code:
    {
        scanf( "%d", &input );
        switch( input)
            {
                case 1:
                    playgame();
                    break;
                case 2:
                    loadgame();
                    break;
                case 3:
                    playmultiplayer();
                    break;
                case 4:
                    printf( "Goodbye\n" );
                    break;
                default:
                    printf( "Bad input, try again\n" );
                    break;
            }
        }
        while( input!=4 );
    Did it work, and then If I put in an invalid input (so it uses default) it no longer accepts input....

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    You also need to say something like
    Code:
    if ( scanf( "%d", &input ) == 1 ) {
       // successful input AND conversion, do the switch here
    } else {
      // throw away chars upto the next newline, or EOF
      int ch;
      while ( (ch=getchar()) != '\n' && ch != EOF );
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Take a look at this, and try it. Study it to see what parts of it you want to use, and in what order.

    Code:
    #include <stdio.h>
    
    int main(void) {
       int input;
       do {
     
          printf( "1. Play game\n" );
          printf( "2. Load game\n" );
          printf( "3. Play multiplayer\n" );
          printf( "4. Exit\n" );
          printf(" Your choice: ");
          scanf( "%d", &input );
          printf("\n"); 
    
          /* There are no other functions for this example. Only the users choice is printed to show it's working properly. */
          switch( input)
          {
             case 1:
                //playgame();    
                printf("1 was chosen");  
                break;
             case 2:
                //loadgame();
                printf("2 was chosen");
                break;
             case 3:
                //playmultiplayer();
                printf("3 was chosen");
                break;
             case 4:
                printf( "Goodbye" );
                break;
             default:
                printf( "Bad input, try again" );
                break; // is OK to put here, but not needed, since it is last in order
          }
          printf("\n\n");
       }while(input != 4);
    
       return 0;
    }
    Last edited by Adak; 08-26-2012 at 03:32 AM.

  10. #10
    Registered User
    Join Date
    Aug 2012
    Posts
    10
    While I do not understand very much of the above code, Salem, It gets me out of the program, but doesn't give me another chance to put in a number... right now the block looks like
    Code:
    if( scanf("%d", &input)) {
        switch( input)
            {
                case 1:
                    playgame();
                    break;
                case 2:
                    loadgame();
                    break;
                case 3:
                    playmultiplayer();
                    break;
                case 4:
                    printf( "Goodbye\n" );
                    break;
                default:
                    printf( "Bad input, try again\n" );
                    break;
            }
        }else {
      // throw away chars upto the next newline, or EOF
      int ch;
      while ( (ch=getchar()) != '\n' && ch != EOF );
    }
    Is it really that bad to use goto in a situation like this? It is pretty obvious what the goto does, and the program works exactly how I want it... although I still want to figure out how to do this without the goto...
    Last edited by .:Lyle:.; 08-26-2012 at 03:33 AM.

  11. #11
    Registered User
    Join Date
    Aug 2012
    Posts
    10
    When I compile and run this code, and I input a a letter/number above 4 so that it uses default, the output says bad output, try again and it scrolls as it prints to infinity and beyond....
    #include <stdio.h>


    int main(void) {
    int input;
    do {

    printf( "1. Play game\n" );
    printf( "2. Load game\n" );
    printf( "3. Play multiplayer\n" );
    printf( "4. Exit\n" );
    printf(" Your choice: ");
    scanf( "%d", &input );
    printf("\n");

    /* There are no other functions for this example. Only the users choice is printed to show it's working properly. */
    switch( input)
    {
    case 1:
    //playgame();
    printf("1 was chosen");
    break;
    case 2:
    //loadgame();
    printf("2 was chosen");
    break;
    case 3:
    //playmultiplayer();
    printf("3 was chosen");
    break;
    case 4:
    printf( "Goodbye" );
    break;
    default:
    printf( "Bad input, try again" );
    break; // is OK to put here, but not needed, since it is last in order
    }
    printf("\n\n");
    }while(input != 4);

    return 0;
    }

    Thank you for helping though...
    Last edited by .:Lyle:.; 08-26-2012 at 03:40 AM.

  12. #12
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Is it really that bad to use goto in a situation like this? It is pretty obvious what the goto does, and the program works exactly how I want it... although I still want to figure out how to do this without the goto...
    The reason why your original program works has nothing to do with using goto.

    If you carefully look at your original code you will notice that after scanf() you call getchar() which will remove the next character from the input buffer. Thus if you only enter one character (doesn't matter if valid or not) this getchar() will remove the newline-character from pressing the enter-key from the input buffer.

    If you want to stay in the program you have to put the while-loop Salem suggested inside your original while loop (input != 4):
    Code:
    do
    {
        scanf("%d", &input);
        switch (input)
        { ... }
        int ch;
        while ((ch=getchar()) != '\n' && ch != EOF)
            ;
    } while (input != 4);
    Bye, Andreas

  13. #13
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I was addressing the "get rid of the goto" logic problem, not input. Add the while loop mentioned just above this post, and post back if you are still having problems.

  14. #14
    Registered User
    Join Date
    Aug 2012
    Posts
    10
    Code:
      #include <stdio.h>
     
    int main(void) {
       int input;
       
      
          printf( "1. Play game\n" );
          printf( "2. Load game\n" );
          printf( "3. Play multiplayer\n" );
          printf( "4. Exit\n" );
         do{    int ch; 
        printf(" Your choice: ");
          scanf( "%d", &input );
          printf("\n");
        getchar();
     
          /* There are no other functions for this example. Only the users choice is printed to show it's working properly. */
          switch( input)
          {
             case 1:
                //playgame();   
                printf("1 was chosen"); 
                break;
             case 2:
                //loadgame();
                printf("2 was chosen");
                break;
             case 3:
                //playmultiplayer();
                printf("3 was chosen");
                break;
             case 4:
                printf( "Goodbye" );
                break;
             default:
                printf( "Bad input, try again" );
                break; // is OK to put here, but not needed, since it is last in order
          }    while((ch=getchar()) != '\n' && ch != EOF);
          printf("\n\n");
       }while(input != 4);
     
       return 0;
    }
    This almost works perfectly, unless I input a valid number and then an invalid input, in which case it still says that I inputed the valid number...
    Last edited by .:Lyle:.; 08-26-2012 at 01:28 PM.

  15. #15
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Quote Originally Posted by .:Lyle:. View Post
    This almost works perfectly, unless I input a valid number and then an invalid input, in which case it still says that I inputed the valid number...
    When you don't input a number, scanf() won't read anything and input is still set to the last valid number.
    Thus either check the return value of scanf() (it will be 0 if it couldn't read anything) or simply set input at the beginning of the do-while-loop to an invalid number (e.g. input = 0).

    Bye, Andreas

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alternative to ifstream?
    By bengreenwood in forum C++ Programming
    Replies: 2
    Last Post: 10-24-2009, 11:12 AM
  2. Alternative to malloc
    By stellastarr in forum C Programming
    Replies: 13
    Last Post: 04-30-2007, 04:10 PM
  3. Any alternative?
    By sCandal2 in forum Windows Programming
    Replies: 4
    Last Post: 01-11-2006, 04:30 PM
  4. gets() alternative
    By Mastadex in forum C Programming
    Replies: 5
    Last Post: 12-12-2004, 12:28 AM
  5. alternative to cin
    By Unregistered in forum C++ Programming
    Replies: 18
    Last Post: 06-25-2002, 05:14 PM

Tags for this Thread