Calling main function from another function in C

别等时光非礼了梦想. 提交于 2019-12-10 20:57:13

问题


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.


回答1:


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.




回答2:


just wrap your main into infinity-loop.

int main(void)
{
    int init_val = 0;
    while (1)
    {
        // your code ...
        init_val = some_function();
    }
}



回答3:


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.



来源:https://stackoverflow.com/questions/25213829/calling-main-function-from-another-function-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!