Jack Jack - 2 months ago 12
C Question

how to jump back to the top of a program

I have a large block of code inside main and would like to return to the top of main and run through again if a certain variable in 'code' is true. How would I do this?

#include <stdio.h>

void main(void)
{

// if varable in code is true return to here



//code
//
//
//


}

Answer

Remove the code from main() and put it in a function:

static void my_function(void)
{
  /* lots of stuff here */
}

Then just call it:

int main(void)
{
  my_function();
  if(condition)
    my_function();
  return 0;
}

This is way cleaner than using a loop, in my opinion, since the use case was not really "loop-like". If you want to do something once or twice, break it out into a function then call the function once or twice. As a bonus, it also gives you a great opportunity to introduce a name (the function name) for the thing that your program is doing, which helps make the code easier to understand.