It's true that writing the same lines of code is not good programming, and would be better this approach, but does this bring to problems of any kind? will the variables created still exist, so am I wasting memory?
What do actually happens when I recall foo() ?
#include <stdio.h>
int foo(){
printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
printf("\n> ");
unsigned int choice;
scanf("%d",&choice);
while (choice!=3){
if (choice==1){
// stuff
} else if (choice==2){
// stuff
} else {
printf("\nError, try again..\n");
foo(); // what happens? does this bring to problems of any kind? will the variables created still exist, so am I wasting memory?
}
}
printf("\nEnd of run.\n");
}
or
#include <stdio.h>
int foo(){
printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
printf("\n> ");
unsigned int choice;
scanf("%d",&choice);
while (choice!=3){
if (choice==1){
// stuff
} else if (choice==2){
// stuff
} else {
printf("\nError, try again..\n");
printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
printf("\n> ");
scanf("%d",&choice);
}
}
printf("\nEnd of run.\n");
}
What's the best approach? I have also read that calling main() for example, is not good programming.
I'm assuming that the loop is supposed to run until the user enters '3'. The main problem then seems to be that you want the usage printed once at the beginning, but then again for each invalid input. One way of doing this, without changing too much of your code, would be like this:
#include <stdio.h>
void print_usage(void){
printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
printf("\n> ");
}
int foo(){
print_usage();
unsigned int choice;
do {
scanf("%d",&choice);
if (choice==1){
// stuff
} else if (choice==2){
// stuff
} else if(choice!=3){
printf("\nError, try again..\n");
print_usage();
}
} while (choice!=3);
printf("\nEnd of run.\n");
}
By doing it like this, scanf()
will be executed in each iteration (so the user can enter '1' or '2' as often as they like), and the problem with the duplicated code is solved be putting that part into a small separate function.
Please note that this code doesn't actually behave the same way as either of your versions. It works like i guess you would probably want it to work.