Why is my code making me do this?

For some reason i need to declare string Guess twice to get it to work.
https://pastebin.com/AuW1v23A
Once in main() and once in GetGuess(). Shouldn’t this give me an error because of double declaration?

I solved it but i dont know how.

That is because of the “scope” issue that Ben talked about. Each declaration is valid only within its own scope (for now, we can consider a scope to be a block of code within curly braces, like a function definition for example). Let’s take a look at some parts of your code:

string GetGuess() {
    //get guess from player
    string Guess = "";
    getline(cin, Guess);
    return Guess;
}

Inside the GetGuess() function, “Guess” is declared, initialized, used as a parameter to the getline() function, and returned. This declaration is available only inside the GetGuess() function, not anywhere else.

int main() {
    PrintIntro();
    string Guess = "";
    GetGuess();

    //repeat guess back to player
    cout << endl;
    cout << "Your guess was: " << Guess << endl;

    return 0;
}

In the main() function, you kept the part where the Guess is printed back to the player. Because you used a variable called “Guess” when printing to the output stream, the compiler probably complained about not knowing what that variable was (in this scope). You solved it by declaring and initializing “Guess” inside main() as well, which made the compiler happy.

Note, however, that each scope has its own variable called “Guess”, and these variables are completely unrelated in your code. So, the value of “Guess” by the end of GetGuess() is whatever the player entered, while the value of “Guess” in main() when printing back to the player is an empty string as it was initialized. That is why we will probably make use of the return type from GetGuess() in future sections, so that main() can also know about what the user entered.

Privacy & Terms