Calling main function from another function in C

2019-07-04 19:03发布

I have a main function that runs a few functions during initialization and then runs a while loop that waits for commands from the UART.

When I see a specific command (let's say reset), I call a function that returns a value. I want to do the following things:

  1. Save the returned value
  2. Start the main function again with the returned value. The returned value is required during initialization of the functions in main.

I am newbie in C and I am not able to figure out a way save variable value in main.

3条回答
萌系小妹纸
2楼-- · 2019-07-04 19:49

The way I understand things, you essentially have the following setup:

int main(int argc, char *argv[]) {
    int value = something_from_last_reset;
    perform_initialization(value);
    while(1) {
        int next_command = wait_for_command();
        if(next_command == RESET_COMMAND) {
            value = get_value();
            // somehow restart main() with this new value
        }
    }
    return 0;
}

Here's one approach you could take:

// global
int value = some_initial_value;

void event_loop() {
    while(1) {
        int next_command = wait_for_command();
        if(next_command == RESET_COMMAND) {
            value = get_value();
            return; // break out of the function call
        }
    }
}

int main(int argc, char *argv[]) {
    while(1) {
        perform_initialization(value);
        event_loop();
    }
    return 0;
}

This essentially lets you "escape" from the event loop and perform the initialization all over again.

查看更多
迷人小祖宗
3楼-- · 2019-07-04 19:54

In theory this is possible, but it kind of breaks paradigms, and repetitively calling a function without ever letting it finish and return will quickly fill up your call stack, unless you take measures to unwind it behind the compiler's back.

A more common solution would be to write your main() function as one giant infinite while {1} loop. You can do all of your operation in an innner loop or whatever, and have clauses such that if you get your desired new value you can fall through to the bottom and loop back, effectively re-running the body of main with the new state.

查看更多
forever°为你锁心
4楼-- · 2019-07-04 19:58

just wrap your main into infinity-loop.

int main(void)
{
    int init_val = 0;
    while (1)
    {
        // your code ...
        init_val = some_function();
    }
}
查看更多
登录 后发表回答