Assigning value of PlayGame() to bLevelComplete also runs PlayGame()...?

Okay I’m just having a bit of a weird time trying to understand how this works. We went from this:

int main ()
{
    while (true)
    {
        PlayGame();
        std::cin.clear();
        std::cin.ignore();
    }

    return 0;
} 

to this:

int main ()
{
    while (true)
    {
        bool LevelComplete = PlayGame();
        std::cin.clear();
        std::cin.ignore();
    }

    return 0;
} 

My question is, does the line “bool LevelComplete = PlayGame();” not only assign the bool return value of PlayGame() to Level Complete, but also run the PlayGame() function…? I would’ve assumed it would only assign one value to the other and not also run the PlayGame function…but apparently it does. I just want to be clear as to what’s going on here.

You are right. The PlayGame() function runs, and the return value of the function gets assigned to LevelComplete.

1 Like

Came here to ask this, as this wasn’t really explained.

I guess c++ has evolved this way because programmers have been employing it as a programming “shortcut” or technique?

Out of curiosity, is there a way to override this behaviour, if you just want to initialize variables to a function, but dont want the function to run at that time?

This is how functions are meant to be used. You call them and they (potentially) return values. e.g.

int square(int n)
{
    return n * n;
}
int main()
{
    int value = square(2); //call square with 2, returns 4, value == 4
    value = square(5); // value now holds 25
}

To be clear, that code isn’t being initialised to a function. It 's being initialised to what the function returns.

It’s a completely different syntax. Such usage is not beginner level and more advanced. I’m curious as to why you want to do that.

1 Like

I was curious about this question too.
You can check how code is executing using this site:
http://www.pythontutor.com/visualize.html#mode=edit
I have simplified code that was provided on the course and checked how exactly while loop is executed (you can also check it just not forget to select C++ language in the editor)

include

bool PlayGame()

{

// Declare 3 number code

int CodeA = 4;

int CodeB = 5;



//Store Player's Guesses

int GuessA =5; 

int GuessB =6;



//Check whether conditions are met

if (CodeA == CodeB && CodeB == GuessB)

{

    std::cout<< "You Win!\n";

    return true;

}



else 

{

    std::cout<<"You Lose!\n";

    return false;

} 

int main()

{ while(true)

{

bool bLevelComplete = PlayGame();

}

return 0;

}