My for loop, lecture_21

My take on it.
My int main() is not as pretty but I wanted to try out to give the functions some parameter input.

Your main() may not be “as pretty”, but your GetGuess() is quite interesting. Bravo on breaking up the guess input and output. I only have 1 question about your function. Why are you passing the Guess variable to it from your main()? To me, it looks like you’re effectively updating the Guess variable twice. You either don’t need p_guess or don’t need GuessToReturn. I would like to know your logic behind it, though.

Do you mean the Guess = GetGuess(Guess) in main?
Guess is empty at the beginning, Guess = “”;
I pass it in to GetGuess(std::string variable) so the function returns the guessed word to my variable Guess.

Inside of the GetGuess() function you can indeed remove std::string GuessToReturn and just return the parameter variable. That way would look way better, thanks!

std::string GetGuess(std::string p_guess){
      std::cout << "Your guess: ";
      std::getline(std::cin, p_guess);
     return p_guess;

Thanks for the input, I was indeed doing more work than needed ^^

Ahh. I understand your logic now. I can help clarify something on that.

Whenever you’re trying to return a value from a function, you don’t need to pass the variable as a parameter. You just need to make sure that the return type is compatible with where it’ll be dropped into.

The whole idea of GetGuess is to query the player for information and pass it back to whatever called it. You can actually do just fine like this:

Guess = GetGuess();
std::string GetGuess() {
    std::string PlayerGuess = "";
    std::cout << "Your guess: ";
    std::getline(std::cin, PlayerGuess);

    return PlayerGuess;

There are times when you would need to pass variables to your functions in order for them to change, but we haven’t hit on a situation where that is needed. Of course, you can take this all with a grain of salt. As long as the code works, it’s perfectly fine. And kudos for reducing your code’s workload.

1 Like

Privacy & Terms