How to get the value that is returned from a function without running the function again?
For example:
int difficulty() {
char x;
while (true) {
if (kbhit()) {
x = getch();
if (x == '1' || x == '2' || x == '3') {
return x;
break;
}
}
}
cout << "done";
}
This function is called in:
void Move(){
if (HeadY >= Height-1 || HeadY <= 0 || HeadX >= Widht-1 || HeadX <= 0)
Lose = false;
char level=diffculty(); //**********
if(level=='2' || level=='3'){
for(int i=0;i<Ta_N;i )
if(HeadX==Ta_X[i] && HeadY==Ta_Y[i])
Lose = false;
}
}
And called in the menu function:
void menu(){
if(kbhit()){
x=getch();
if(x=='s' || x=='S'){
system("cls");
table();
while(Lose){
Line();
Input();
Move(); //***********
Sleep(50);
}
system("pause");
}
}
I need the x
value only to compare it, but it runs the code again??
CodePudding user response:
I am assuming you want to create x
in menu()
and then store it as a variable to pass down the chain of function calls started in menu()
.
Under this assumption what you ought to do is simple. menu()
becomes:
void menu(){
if(kbhit()){
char x=getch(); // CHANGED
if(x=='s' || x=='S'){
system("cls");
table();
while(Lose){
Line();
Input();
Move(x); //CHANGED
Sleep(50);
}
system("pause");
}
}
}
Then Move()
should be modified into Move(char x)
:
void Move(char x){ // CHANGED
if (HeadY >= Height-1 || HeadY <= 0 || HeadX >= Widht-1 || HeadX <= 0)
Lose = false;
char level = difficulty(x); // CHANGED
if (level=='2' || level=='3'){
for (int i=0;i<Ta_N;i )
if (HeadX==Ta_X[i] && HeadY==Ta_Y[i])
Lose = false;
}
}
difficulty()
becomes difficulty(char x)
char difficulty(char x) { //CHANGED
// DELETED LINE char x;
// REDUNDANT AS EXPLAINED IN COMMENT BELOW while (true) {
// REDUNDANT if (kbhit()) {
// DELETED LINE x = getch();
if (x == '1' || x == '2' || x == '3') {
return x;
// DELETE THIS break;
} else
throw("what happens when x != 1 or 2 or 3?"); //ADDED
// REDUNDANT } else
// REDUNDANT throw("what happens when kbhit() is false?");
// REDUNDANT }
cout << "done";
}