i need to show a menu that derive another menu and this derive another menu. But i'm validating those menus with this form: (Only C standard library)
do{
validOption = 1;
printf("Option #1\n");
printf("Option #2\n");
printf("Option #3\n");
scanf("%i",&option);
switch(option){
case 1: /* Do something */ break;
case 2: /* Do something */ break;
case 3: /* Do something */ break;
default: validOption = 0; printf("Invalid Option\n"); break;
}
}while(!validOption);
But at the time of derive a menu i dont know if use the same option
variable and validOption
flag.
I think that is not a problem since the derived option
variable is going to be overwritten and
I will not need the previous option
variable since that option
variable has been used for its only
purpose that is join in a specific case.
Now, validOption
flag is not a problem too, since when a successfully case occurs means that validOption = 1
(will not iterate more)
and it will match with the previous validOption
that have a value of 1 (since has been joined in a case). So will not interfere.
Is a good practice to use the same variables (option, validOption
) within derived menus?
Also i need to validate with a getint()
function, which make me think that if
is even necessary validate menus seeing it in a practical way.
#include<stdio.h>
int main(){
int option;
int validOption;
do{
printf("Option #1\n");
printf("Option #2\n");
printf("Option #3\n");
scanf("%i",&option);
switch(option){
case 1:
validOption = 1;
do{
printf("Option #1\n");
printf("Option #2\n");
printf("Option #3\n");
scanf("%i",&option);
switch(option){
case 1: validOption = 1; /* Another menu with the same option and validOption variables */ break;
case 2: validOption = 1; /* Do something */ break;
case 3: validOption = 1; /* Do something */ break;
default: validOption = 0; printf("Invalid Option\n"); break;
}
}while(!validOption);
break;
case 2: validOption = 1; /* Do something */ break;
case 3: validOption = 1; /* Do something */ break;
default: validOption = 0; printf("Invalid Option\n"); break;
}
}while(!validOption);
return 0;
}
//I've put validOption = 1; within all cases just for explaining purposes
I would rather call it nested loop than derived.
Coming to your question: Is it valid to re-use same variable within a loop when the 1st value of the variable is no longer needed? (Am I right in rephrasing your question?)
Yes, it's valid. While there's nothing technically wrong with it, I would say No. Because, it causes unnecessary confusion and makes the code readability difficult especially when you it within the same loop (as you do within your outer loop). It becomes even harder as the code base grows. Hence, I would discourage such a coding practice.
You want to validate your integer: Since, you are only going to do pass-by-value (to getint()
), there's no problem in using another variable. You can use option1
and option2
Pass the values to getint()
to validate it.