Order of execution L23

Im trying to understand the order the code is being executed in the PlayGame function and it is a little confising.

The code thats confusing me is: cout << "You entered: " << Guess << endl;

I expect “You entered:” to be output before the GetGuess function is called but its the opposite, why is that?

void PlayGame()
{
const int NUMBER_OF_TURNS = 5;
for (int count = 1; count <= NUMBER_OF_TURNS; count ++){

string Guess = GetGuess();
cout << "You entered: " << Guess << endl;
cout << endl;

}

}

if i’m understanding your code correctly you put the GetGuess function for the value of Guess? Then use the cout to output the Guess?

Correct, that is what I have done. :slightly_smiling_face:

i put the GetGuess function equal to the value of Guess. Then use the cout to output the Guess.

I think a more valid question is:
“Why would you expect the program to not initialize the variable ‘Guess’ before trying to print out the value of that variable?”

Would you skip around in the instruction manual when assembling an automobile or would you follow it step by step?

Oh ok, don’t get confused by what is running first in playgame(). the code was written so that the int guess needs a value, so GetGuess() was used for that purpose so that you can ouput through the command line. In all, everything runs through your int main function and how the code is written from there. The other functions we written like getGuess() are just seperated small task that we can call from our main in order for the game to work as intended.

When your code reaches this moment:

string Guess = GetGuess();

… it basically realises that the string is being created and the value of it is a result of a method/function. It needs the value. So it executes the GetGuess() function in order to assign the result it needs. Once Guess has a value it can then proceed to the next line (cout << (…and so on…)) and output what’s already stored in the string that happened in the line above :slight_smile: If you would technically (I didn’t test the below) write something along the lines of:

    void PlayGame()
    {
    const int NUMBER_OF_TURNS = 5;
    string Guess = "";
    for (int count = 1; count <= NUMBER_OF_TURNS; count ++){

    cout << "You entered: " << GetGuess() << endl;
    cout << endl;

    }
    }

You would get the result you expected in the first place…

Privacy & Terms