Calling a main function from another function in C
I have a main function that performs several functions during initialization and then starts a while loop waiting for commands from the UART.
When I see a certain command (say reset), I call a function that returns a value. I want to do the following:
- Save return value
- Run the main function again with the returned value. The return value is required during the initialization of the main functions.
I'm new to C and I can't seem to find a way to store the value of a variable in the main.
source to share
As I understand it, 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 you can choose one of the following methods:
// 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 allows you to "escape" the event loop and initialize over and over again.
source to share
In theory this is possible, but it's kind of like the paradigms of discontinuities and re-calling a function without letting it finish and return will quickly fill your call stack unless you take steps to deploy it behind the compiler.
A more common solution would be to write main () as one giant infinite loop {1}. You can do all of your work in an innner office or whatever, and have it in such a way that if you get the new value you want, you can sink to the bottom and go back, effectively rerun main with the new state.
source to share