user2719475
user2719475

Reputation:

C++ variable value saved after recalling function

I don't understand the behaviour of the following code:

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;

bool playGame() {

    //game procedure here

    cout<<"Would you like to play again (y or n)? ";

    char choice;    //the problem here <<------
    while(!(choice == 'n' || choice == 'y')) {
        cin>>choice;
    }

    if(choice == 'y')
        return true;
    else
        return false;
}

int main() {
    bool play = true;

    while(play){
        play = playGame();
    }

    return 0;
}

Suppose i enter 'y' for the variable choice the first time the playGame() is called. This value will be saved for the consecutive calls of playGame() in the variable choice, and while loop will not get executed. Why is that?

Upvotes: 0

Views: 126

Answers (1)

R Sahu
R Sahu

Reputation: 206667

Your program has undefined behavior since you are using choice before initializing it.

We can try to explain the behavior but that's pointless when you are looking at undefined behavior.

Initialize choice to a sensible value and your program will be well behaved.

char choice = {};  // Initializes choice to zero.
while(!(choice == 'n' || choice == 'y')) {
    cin>>choice;
}

I would write the code to check whether the input is valid a bit differently though, using a helper function.

bool isValidInput(char choice)
{
    return (choice == 'n' || choice == 'y');
}

...


char choice = {};  // Initializes choice to zero.
while( !isValidInput(choice) ) {
    cin>>choice;
}

Upvotes: 3

Related Questions