Esoteric strategies
The @Ruy Neto answer is about the principal. But the question is not limited to practical resolutions, it reminds one more exercise. Since it's an exercise, let's exercise?
goto
int main() {
int op;
goto INICIO;
SAIDA:
saudacoes_tchau();
return 0;
INICIO:
saudacoes_oi();
VOLTA:
op = le_operacao();
trata_operacao(op);
if (op) {
goto VOLTA;
} else {
goto SAIDA;
}
}
The goto
will force an unconditional jump to some place pointed to in the code 1 . In case, for VOLTA
, the command soon after saudacoes_oi()
1: in the case of C, and in some other languages that support goto
, the "place indicated in the code" is not totally arbitrary; it must be within the same function. If I'm not mistaken, in Pascal,% w /% could go to any arbitrary point in the system, leaving the code stream more macaronic than "normal"; luckily C does not allow this, has the constraint of being in the same function
Direct recursion of function, tail condition
void funcao_menu() {
int op;
op = le_operacao();
trata_operacao(op);
if (op) {
funcao_menu();
}
}
int main() {
saudacoes_oi();
funcao_menu();
saudacoes_tchau();
return 0;
}
Recursively calling the function to handle the operations available in the menu. Note that here I always run the entire function for, so choose if I should make the call, in the tail, of the function.
Indirect recursion of function, function pointer
void funcao_menu() {
void (*proxima_chamada)();
int op;
proxima_chamada = &saudacoes_tchau;
op = le_operacao();
trata_operacao(op);
if (op) {
proxima_chamada = &funcao_menu;
}
(*proxima_chamada)();
}
int main() {
saudacoes_oi();
funcao_menu();
return 0;
}
Now, the choice is made between calling goto
or the function itself.
Direct recursion of the function, condition in the argument
void funcao_menu(int old_op) {
int op;
if (old_op) {
op = le_operacao();
trata_operacao(op);
funcao_menu(op);
}
}
int main() {
saudacoes_oi();
funcao_menu(1);
saudacoes_tchau();
return 0;
}
Here, who defines whether there will be recursion or not is the function parameter. If a true argument is passed, it is executed; otherwise, close the loop.
Indirect recursion function, mutually recursive functions
void funcao_menu();
void trata_operacao_chama_funcao_menu(int op) {
if (op) {
trata_operacao(op);
funcao_menu();
}
}
void funcao_menu() {
trata_operacao_chama_funcao_menu(le_operacao());
}
int main() {
saudacoes_oi();
funcao_menu();
saudacoes_tchau();
return 0;
}
tchau
calls trata_operacao_chama_funcao_menu
calling funcao_menu
.
Recursion using system calls
For this, I'm going to remove the trata_operacao_chama_funcao_menu
greeting because it's hard to define when it should be done.
int main(int argc, char **argv) {
int op = le_operacao();
if (op) {
trata_operacao(op);
return system(argv[0]);
}
return 0;
}