my c++ contains a conditional loop but its producing a infinite loop
1 hour ago, HunterAP said:Just change:
AskToPlayAgain(); bPlayAgain = AskToPlayAgain;To:
bPlayAgain = AskToPlayAgain();
When you run the first line in the first snippet of code, the return value of the function is not stored anywhere, and it's just thrown away.
When you run the second line of that same snippet, you're calling the memory address of the function, which for all intents and purposes of this code is simply running the function again.
Using parenthesis for function calls is a basic and fundamental part of basically all C based programming. Make sure not to do something like this is future programs: always remember to use parenthesis when you call functions.
The second code snippet that is just one line fixes your problem: it only calls the function twice, and makes sure that it is stored in a variable that you can use later, and it has the parenthesis in it to prevent issues with calling the function.
The final main function should look like this:
int main() { bool bPlayAgain = false; do { PrintIntro(); PlayGame(); bPlayAgain = AskToPlayAgain(); } while (bPlayAgain); return 0; // exit the application }
15 hours ago, Unimportant said:
First of all, as already mentioned, you probably want to call AskToPlayAgain only once, but the second call, missing the () results in different behavior:
AskToPlayAgain(); bPlayAgain = AskToPlayAgain; //<== AskToPlayAgain, without (), does not call the function but decays into the function's memory address. //Since the memory address will never be 0 it will always result in bPlayAgain being set to true.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now