Search code examples
cgoto

goto vs return for submenus and menus in C programming


I I have a really quick question. Which is more "standard" to use? goto or returning a function?

goto example:

main(){
   start:
   //some code
   goto start;
}

main(){
   //some code
   return main();
}

Both will loop the script. but I am wondering which one is more proper to use.

goto seems to be really good, but are there any disadvantages to using it? (I'm just wondering because an instructor failed a fellow student because of the goto function O.o and I'm wondering why, or what he did was reasonable.)

If you're asking why ask this, I am trying to create a menu with a submenu, where the submenu contains a "back" option (Where I would either use goto or return)


Solution

  • Here the reasonable thing to do is to use a loop. It has the same effect as a goto but is considered better practice as it follows the rules of structured programming as opposed to the unmaintainable noodle soup programming that was common before.

    int main(void) {
       while (1) {
          //some code
       }
    }
    

    Calling a function recursively could also be considered good style if the recursion had well-defined limits. Unlimited recursion in C usually leads to a stack overflow error, since few compilers implement tail-call optimization.