Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling main function from another function in C

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.

like image 575
rohit Avatar asked Aug 09 '26 13:08

rohit


2 Answers

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.

like image 50
Ethereal Avatar answered Aug 11 '26 03:08

Ethereal


just wrap your main into infinity-loop.

int main(void)
{
    int init_val = 0;
    while (1)
    {
        // your code ...
        init_val = some_function();
    }
}
like image 32
ikh Avatar answered Aug 11 '26 04:08

ikh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!